C++, Sort One Vector Based On Another One [duplicate]

An alternative to consolidating the names and scores into a single structure is to create an index list and sort that:

 std::vector<int> indices(Names.size());
 std::iota(indices.begin(), indices.end(), 0);
 std::sort(indices.begin(), indices.end(),
           [&](int A, int B) -> bool {
                return Score[A] < Score[B];
            });

Now indices can be used to index Names and Scores in the desired sorted order.

Leave a Comment