【发布时间】: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)} };
我已经尝试了几个小时,但找不到它。
【问题讨论】:
-
int x[]是一维数组
我想在排序后跟踪值的原始位置。
不久前我看到了一个解决方案,但我把它弄丢了,它是使用多组和对完成的。
int x[2][2] = { {3, 2}, {1, 4}};
sorted_x = { {4,(1,1)}, {3,(0,0)}, {2,(0,1)}, {1,(1,0)} };
我已经尝试了几个小时,但找不到它。
【问题讨论】:
int x[] 是一维数组
您可以填充一些包含元素及其索引的容器,然后对其进行排序:
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<(const element_and_index& other) const {。例如,如果你在std::priority_queue<> 中使用它,它就不起作用。