I have several std::vector, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold ints and some of them std::strings.
Pseudo code:
std::vector<int> Index = { 3, 1, 2 }; std::vector<std::string> Values = { 'Third', 'First', 'Second' }; Transformation = sort(Index); Index is now { 1, 2, 3}; ... magic happens as Transformation is applied to Values ... Values are now { 'First', 'Second', 'Third' };
friol’s approach is good when coupled with yours. First, build a vector consisting of the numbers 1…n, along with the elements from the vector dictating the sorting order:
Now you can sort this array using a custom sorter:
Now you’ve captured the order of rearrangement inside
order(more precisely, in the first component of the items). You can now use this ordering to sort your other vectors. There’s probably a very clever in-place variant running in the same time, but until someone else comes up with it, here’s one variant that isn’t in-place. It usesorderas a look-up table for the new index of each element.