C++, Sort One Vector Based On Another One

前端 未结 7 717
粉色の甜心
粉色の甜心 2020-12-01 21:25

The best example I\'ve got is that I want to sort Names based on their Score.

vector  Names {\"Karl\", \"Martin\", \"Paul\", \"Jennie\"};
vecto         


        
相关标签:
7条回答
  • 2020-12-01 21:44

    Couldn't this be done through a custom iterator type?

    EDIT:

    What I'm thinking in its simplest form - sorting a pair of vectors based on the first one - is to have an iterator whose functions such as dereferencing, subscripting, member access and equality and ordering comparisons would call the corresponding functions on the first iterator, all other functions (copy, arithmetics, swap, ...) acting on both iterators.

    template <typename Driver, typename Passenger>
    struct duo_iterator { . . . };
    
    template <typename D, typename P>
    auto make_duo_iterator(D d, P p) -> duo_iterator<D, P> { . . . }
    
    sort(make_duo_iterator(begin(v1), begin(v2)),
         make_duo_iterator(end(v1), end(v2)));
    

    The iterator could be extended into a multi_iterator to work with any reordering algorithm, pointing into any number of extra piggybacking sequences.
    It could be a fun little project. Or maybe something similar already exists, in Boost or elsewhere.

    EDIT2:

    Forget the above.
    Eric Niebler's Range-v3 library has a view::zip wrapper that "Given N ranges, return a new range where Mth element is the result of calling make_tuple on the Mth elements of all N ranges."
    Sorting the range with a predicate on the first element of the tuples might just do the trick.

    0 讨论(0)
提交回复
热议问题