D
D
dansheb2016-01-08 18:14:46
C++ / C#
dansheb, 2016-01-08 18:14:46

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

3 answer(s)
A
AtomKrieg, 2016-01-08
@dansheb

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;

A
Alexander Movchan, 2016-01-08
@Alexander1705

Make a vector of pairs std::vector<std::pair<int, char>>, and std::sortpass 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;});

M
maaGames, 2016-01-08
@maaGames

Make your object a comparator, in which store a pointer to the second array. In the comparison operator, not only compare the values ​​of the arguments, but also swap the values ​​in the second array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question