Home C++ 得到 vector 排序后的索引
Post
Cancel

C++ 得到 vector 排序后的索引

直接看例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> test = {1, 2, 3, 4, 5, 9, 8, 7, 6, 0};
    vector<int> index(test.size());
    iota(index.begin(), index.end(), 0);
    sort(index.begin(), index.end(), [&test](int i1, int i2) { return test[i1] < test[i2]; });

    for (const auto &i : index)
        cout << i << " ";

    return 0;
}

输出结果

1
9 0 1 2 3 4 8 7 6 5 
This post is licensed under CC BY 4.0 by the author.