A very good discussion of this problem can be found here: https://web.archive.org/web/20120422174751/http://www.stanford.edu/~dgleich/notebook/2006/03/sorting_two_arrays_simultaneou.html
Here is a possible duplicate of this question: Sorting compressed (locked) containers in C ++ using boost or STL
The connection above uses std :: sort with no extra space. It does not use boost :: zip_iterator, it simply increases the tuples and facade of the boost iterator. Std :: tuples should also work if you have a modern compiler.
If you are happy to have one additional vector (from the elements of size_t), then the following approach will work in a tool with a time interval of ~ o (n log n). It's pretty simple, but there will be better approaches if you find them.
#include <vector> #include <iostream> #include <algorithm> #include <iterator> using namespace std; template <typename T1, typename T2> void sortByPerm(vector<T1>& list1, vector<T2>& list2) { const auto len = list1.size(); if (!len || len != list2.size()) throw; // create permutation vector vector<size_t> perms; for (size_t i = 0; i < len; i++) perms.push_back(i); sort(perms.begin(), perms.end(), [&](T1 a, T1 b){ return list1[a] < list1[b]; }); // order input vectors by permutation for (size_t i = 0; i < len - 1; i++) { swap(list1[i], list1[perms[i]]); swap(list2[i], list2[perms[i]]); // adjust permutation vector if required if (i < perms[i]) { auto d = distance(perms.begin(), find(perms.begin() + i, perms.end(), i)); swap(perms[i], perms[d]); } } } int main() { vector<int> ints = {32, 12, 40, 8, 9, 15}; vector<double> doubles = {55.1, 33.3, 66.1, 11.1, 22.1, 44.1}; sortByPerm(ints, doubles); copy(ints.begin(), ints.end(), ostream_iterator<int>(cout, " ")); cout << endl; copy(doubles.begin(), doubles.end(), ostream_iterator<double>(cout, " ")); cout << endl; }
Carl Cook Sep 19 '13 at 21:54 on 2013-09-19 21:54
source share