首页 > 解决方案 > 在 C++ 排序中指定比较函数的参数

问题描述

我的问题是 C++ 排序函数中的比较函数如何接受参数。如果我想对数组进行排序但又想保留元素的索引,我想根据实际数组中的元素对索引数组进行排序。问题是我无法找到如何将参数传递给比较函数。假设数组是 3 5 4 2 索引是 0 1 2 3 。我想要索引数组输出 3 0 2 1 ,即 2 3 4 5 。我怎样才能使用排序功能做到这一点。

标签: c++sortingc++11stl

解决方案


一种方法:

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 << ' ';
}

推荐阅读