【问题标题】:Finding the sorted order of an an array of structs in c++在 C++ 中查找结构数组的排序顺序
【发布时间】:2018-04-04 14:08:19
【问题描述】:

我有:

int  _size; //array's dimension
int _cont; //number of elements at the moment (<_size)
bool _full;

struct elemento {
    T value;
    int pos;
    elemento *prev;
    elemento *next;
    elemento(): value(0), pos(-1), prev(0), next(0){}
    elemento(const T &v): value(v), pos(-1), prev(0), next(0){}
};
elemento *_array;

我想在不修改原始数组的情况下对其进行排序,除了设置“pos”来保存排序元素的位置。我希望设置一个下一个/上一个指针来面对两个元素的值会很有用,但我不知道怎么做。我做了一个函数

add(elemento v) 

我手动插入每个元素,我正在考虑在v.pos=sort_function(_cont) 调用排序函数,但我不知道如何排序。

【问题讨论】:

  • 这很不寻常。通常,您有某种可以分类的容器。对于频繁更改,列表非常适合。将位置存储在已排序的元素中需要每次插入时完全重新计算所有位置。这是非常低效的。这并不意味着它不能完成,但它不是很有用!
  • 这看起来像一个双链表,而不是一个数组。
  • 这在我看来不是一个明智的设计。如果您想根据不可变数组的内容对指针或索引进行排序,请使用单独的指针或索引数组并对其进行排序。为什么你需要 prev/next 完全是个谜。
  • 谢谢,我想我会使用指针数组,我认为使用结构体会更容易理解,但最终实现起来要复杂得多

标签: c++ arrays sorting struct


【解决方案1】:

您可以创建std::reference_wrapper 的新数组或向量,然后创建std::sort 该容器以获得原始数组的排序“视图”。

例如:

std::vector<std::reference_wrapper<elemento>> sorted_view(std::begin(the_array), std::end(the_array);
std::sort(std::begin(sorted_view), std::end(sorted_view), comparison_function_or_lambda);

【讨论】:

  • std::end(*_array) 不起作用,因为这只是指向第一个元素的指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 2011-05-13
  • 2014-03-12
相关资源
最近更新 更多