我的问题是C++排序函数中的compare函数是如何接受参数的。如果我想对一个数组进行排序,同时又想保留元素的索引,我会考虑根据实际数组中的元素对索引数组进行排序。问题是我不能找到如何将参数传递给比较函数。假设数组是3 5 4 2索引是0 1 2 3.我希望索引数组输出3 0 2 1,即2 3 4 5。我如何使用排序函数来做到这一点。
发布于 2019-11-02 09:13:37
一种方法是:
vector<int> data{ 3, 5, 4, 2 },
index{ 0, 1, 2, 3 };
sort(index.begin(), index.end(), [&data](int i, int j) { return data[i] < data[j]; });
for (int i : index)
{
cout << i << ' ';
}https://stackoverflow.com/questions/58667345
复制相似问题