0

I have two parallel arrays that I want to sort based on the contents of one of them:

void foo(vector<int>& a, vector<int>& b) {
  assert(a.size() == b.size());
  // I want elements in |b| to be sorted the same as elements in |a|.
  sort(a.begin(), a.end());  // Not good: only sorts |a|.
}

Note, that it's trivial to do this with some extra vectors but I'd like to do this in-place. Again, I can probably hand roll some solution, but I was wondering if there's some standard library incantation that could take care of it ...

UPDATE

The suggested 'duplicate' How can I sort two vectors in the same way, with criteria that uses only one of the vectors? uses an extra index array to perform the sort. The whole point of the question is whether we can do that without allocating the extra array. Imagine if the vectors are really huge.

Lajos Nagy
  • 9,075
  • 11
  • 44
  • 55
  • What do you do when `vector A` has different elements than `vector B`? – Thomas Matthews May 24 '23 at 17:33
  • I was basically wondering if there's a way to tell std::sort() to use a custom swap() function. It can use a custom compare() so maybe it can use a custom swap() as well. But maybe there's no easy way to do that ... – Lajos Nagy May 24 '23 at 17:51
  • @LajosNagy according to [cppreference](https://en.cppreference.com/w/cpp/algorithm/sort), the type also need to be "MoveAssignable and MoveConstructible", which indicate it may not actually use `swap`. – apple apple May 24 '23 at 18:35
  • relate: https://stackoverflow.com/questions/14212701/stdsort-does-not-always-call-stdswap – apple apple May 24 '23 at 18:35
  • 4
    There are other answers on the duplicate question, in particular the suggestion to go with `ranges::zip_view`. If you don't have access to C++20 `ranges` or the range-v3 library you would have to replicate the behaviour yourself. afaik this is the only way to archieve what you want. The magic in these solutions is the user defined assignment operator. – chrysante May 24 '23 at 19:38

0 Answers0