C++ sorting and keeping track of indexes

后端 未结 15 2164
甜味超标
甜味超标 2020-11-22 10:01

Using C++, and hopefully the standard library, I want to sort a sequence of samples in ascending order, but I also want to remember the original indexes of the new samples.<

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 10:21

    There is another way to solve this, using a map:

    vector v = {...}; // input data
    map m; // mapping from value to its index
    for (auto it = v.begin(); it != v.end(); ++it)
        m[*it] = it - v.begin();
    

    This will eradicate non-unique elements though. If that's not acceptable, use a multimap:

    vector v = {...}; // input data
    multimap m; // mapping from value to its index
    for (auto it = v.begin(); it != v.end(); ++it)
        m.insert(make_pair(*it, it - v.begin()));
    

    In order to output the indices, iterate over the map or multimap:

    for (auto it = m.begin(); it != m.end(); ++it)
        cout << it->second << endl;
    

提交回复
热议问题