【问题标题】:a pointer points to an object in vector after sorting(C++)排序后指针指向向量中的对象(C++)
【发布时间】:2021-09-20 19:48:28
【问题描述】:

有这样的结构


class Component {
    string name;
    int x;
    int y;
};

struct Relation_h { // also for Relation_v (h for horizontal, v for vertical)
    Component *;
    //some data in here;
};

我有一个初始向量 vector<Component> datavector<list<Relation>> relation_h and relation_v

我想sort the vector data分别对应它的x和y然后构造关系
Component* actually points to the data[i] for i in range(0, data.size())

但问题是the pointer points to is not the original object which I want to access after sorting with x and y

有没有办法处理这种情况?

【问题讨论】:

  • 诀窍可能不是尝试对数据本身进行排序。 See this。简而言之,有一个索引数组并根据原始排序标准对其进行排序。然后使用索引数组以排序的方式访问元素。另外,请发帖minimal reproducible example——当你说你正在对数据进行排序时,我们不知道你在做什么。
  • 另外,这里不需要指针。你有一个对象向量——与指针有什么关系?也许是因为你没有想到按照我在第一条评论中建议的方式做事?
  • @PaulMcKenzie 感谢您的回答,我想对数据进行排序的原因是,当我构建relation_h 或relation_v 只是为了方便直接push_back 时
  • 好吧,我不能轻易地对未显示的代码发布答案。但是根据您的描述,使用索引数组和排序似乎可以轻松实现您的目标。
  • 请不要在问题中编辑答案,如果您已经解决了问题,您可以发布自己问题的答案

标签: c++ sorting pointers


【解决方案1】:

cmets 中提到的一个这样的解决方案(当然,不是唯一的一个)是使用this answer 中描述的辅助索引数组

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <numeric>

//...
struct Component {
    std::string name;
    int x;
    int y;
    Component(int val1, int val2) : x(val1), y(val2) {}
};
//...
int main()
{
    std::vector<Component> vComponents = { {2,3},{1,2},{0,2},{12,-2},{3,4},{-6,1} };

    // Create the index array (0,1,2,3,4,...)
    std::vector<int> index(vComponents.size());
    std::iota(index.begin(), index.end(), 0);

    //Print original
    std::cout << "Original order:\n";
    for (auto i : index)
        std::cout << vComponents[i].x << " " << vComponents[i].y << "\n";

    // Sort the index array, based on the x, y criteria
    std::sort(index.begin(), index.end(), [&](int n1, int n2)
        { return std::tie(vComponents[n1].x, vComponents[n1].y) <
                 std::tie(vComponents[n2].x, vComponents[n2].y); });
    //...
    // Print sorted
    std::cout << "\nSorted order:\n";
    for (auto i : index)
        std::cout << vComponents[i].x << " " << vComponents[i].y << ":    Location is at " << i << "\n";
}

输出:

Original order:
2 3
1 2
0 2
12 -2
3 4
-6 1

Sorted order:
-6 1:    Location is at 5
0 2:    Location is at 2
1 2:    Location is at 1
2 3:    Location is at 0
3 4:    Location is at 4
12 -2:    Location is at 3

有几点需要注意:

  1. 索引数组是已排序的数组。赋予std::sort 谓词的索引用于在vComponents 向量内进行比较。

  2. std::tie 的使用使得比较“级联”成员变得微不足道,例如 xy

然后您可以使用index 数组来访问元素。您保持元素的顺序不变,但具有指示“排序”项所在位置的索引数组。

【讨论】:

    猜你喜欢
    • 2014-12-29
    • 2011-10-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多