【问题标题】:Ordering array values while tracking their original position在跟踪其原始位置的同时对数组值进行排序
【发布时间】:2021-10-15 16:35:39
【问题描述】:

我想在排序后跟踪值的原始位置。

不久前我看到了一个解决方案,但我把它弄丢了,它是使用多组和对完成的。

int x[2][2] = { {3, 2}, {1, 4}};

sorted_x = { {4,(1,1)}, {3,(0,0)}, {2,(0,1)}, {1,(1,0)} }; 

我已经尝试了几个小时,但找不到它。

【问题讨论】:

标签: c++ algorithm sorting stl


【解决方案1】:

您可以填充一些包含元素及其索引的容器,然后对其进行排序:

struct element_and_index {
     int value;
     size_t x;
     size_t y;
     bool operator<(const element_and_index& other) const {
         return value < other.value;
     }
};

std::vector<element_and_index> temp;

// ... populate the vector ....

std::sort(temp.begin(),temp.end());

【讨论】:

  • 操作员签名后面应该有const,这样才能充分发挥效用,所以bool operator&lt;(const element_and_index&amp; other) const {。例如,如果你在std::priority_queue&lt;&gt; 中使用它,它就不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-11
  • 2013-04-27
  • 2014-08-26
  • 1970-01-01
  • 2021-10-15
  • 2015-12-09
  • 1970-01-01
相关资源
最近更新 更多