如果我对您的理解正确,您希望获得一份索引列表。一种解决方案是创建所有元素的索引的无序列表并对其进行排序。
int array[] = {2, 4, 3, 1};
int indices[] = {0, 1, 2, 3};
std::sort(indices, indices + 4, [&](int a, int b) {
return array[b] < array[a];
});
由于您要求使用非 C++11 方式,因此您可以绕过 lambda 表达式,如下所示:
int array[] = {2, 4, 3, 1};
int indices[] = {0, 1, 2, 3};
struct {
int *array;
bool operator()(int a, int b) const
{
return this->array[b] < this->array[a];
}
} customLess = {array};
std::sort(indices, indices + 4, customLess);
两种实现都会对indices 的值进行排序,但不是 array 本身。结果如下所示:
array == {2, 4, 3, 1}
indices == {1, 2, 0, 3}