C++ sorting and keeping track of indexes

后端 未结 15 2297
甜味超标
甜味超标 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:22

    Consider using std::multimap as suggested by @Ulrich Eckhardt. Just that the code could be made even simpler.

    Given

    std::vector a = {5, 2, 1, 4, 3};  // a: 5 2 1 4 3
    

    To sort in the mean time of insertion

    std::multimap mm;
    for (std::size_t i = 0; i != a.size(); ++i)
        mm.insert({a[i], i});
    

    To retrieve values and original indices

    std::vector b;
    std::vector c;
    for (const auto & kv : mm) {
        b.push_back(kv.first);             // b: 1 2 3 4 5
        c.push_back(kv.second);            // c: 2 1 4 3 0
    }
    

    The reason to prefer a std::multimap to a std::map is to allow equal values in original vectors. Also please note that, unlike for std::map, operator[] is not defined for std::multimap.

提交回复
热议问题