Answer the question
In order to leave comments, you need to log in
How to sort two arrays by one of them in C++?
Suppose there are two (or more) std::vector<T> (or std::array<T>) vectors A and B of the same length n.
You need to sort the arrays by A, while rearranging the corresponding elements of B. (This is what spreadsheet processors like Excel do and tables are also processed in the DBMS).
Example for two arrays A and B:
AB
5 R
4 Q
1 T
3 A
2 X
Sort by A:
AB
1 T
2 X
3 A
4 Q
5 R
Additional memory limits O(1) .
From ideas on how to do this using C ++ without libraries:
1. Copy std::sort and replace the std::swap function in it with your own, which rearranges related elements.
2. Overload std::swap for some type to use std::sort without changes, but I don't understand how to do it, because when exchanging two values in std::vector<T>, std:: will be called: swap<T, T>.
The question is how to implement such sorting simply and without rewriting unnecessary code.
Preferably without using additional libraries. (I would also like to see the answers with them).
Answer the question
In order to leave comments, you need to log in
There is such an approach web.stanford.edu/~dgleich/notebook/2006/03/sorting...
or
Put the values in a map - it sorts the values by key
vector<int> intv{5, 4, 1, 3, 2};
vector<char> charv{'R', 'Q', 'T', 'A', 'X'};
map<int, char> res;
for (size_t idx {0} ; idx < intv.size() ; idx++)
res[intv[idx]] = charv[idx];
for (auto kv : res)
cout << kv.first << " " << kv.second << endl;
Make a vector of pairs std::vector<std::pair<int, char>>
, and std::sort
pass in your own comparator that will only compare the first elements:
vector<pair<int, char>> vec;
sort(vec.begin(), vec.end(), [](pair<int, char> a, pair<int, char> b){return a.first < b.first;});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question