Skip to content

Instantly share code, notes, and snippets.

@insaneyilin
Created June 15, 2023 02:16
Show Gist options
  • Save insaneyilin/d88a62c6c8d6942c094ba92f0c0a171e to your computer and use it in GitHub Desktop.
Save insaneyilin/d88a62c6c8d6942c094ba92f0c0a171e to your computer and use it in GitHub Desktop.
c++ sort one vector based on another
vector <string> Names {"Karl", "Martin", "Paul", "Jennie"};
vector <int> Score{45, 5, 14, 24};
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment