Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ sort 2 arrays pairwise [duplicate]

Tags:

c++

sorting

I have 2 std::vectors, one float, one integer: A and B.

A = [5,3,1,2]

B = [0.1, 0.2, 0.3, 0.4]

I want to sort A and maintain the same 1-1 in B. So the result should look like:

A = [1,2,3,5]

B = [0.3, 0.4, 0.2, 0.1]

I used python/js convention for convenience, but these are C++ std::vectors. I was considering just making a tuple struct and packing these into a std:vector of tuples, overloading the sort comparator. Is there more lazy way of doing this?

like image 496
War Donkey Avatar asked Sep 13 '25 18:09

War Donkey


2 Answers

C++ Standard Library conveniently provides std::pair<TFirst,TSecond> template, which has exactly the comparison operator that you are looking for, i.e. sort on pair::first, resolve ties using pair::second:

std::vector<std::pair<int,double>> myVect;
// Replace this with a loop that iterates your vectors on the same index,
// and pushes back pairs from their elements into myVect:
myVect.push_back(std::make_pair(5, 0.1));
myVect.push_back(std::make_pair(3, 0.2));
myVect.push_back(std::make_pair(1, 0.3));
myVect.push_back(std::make_pair(2, 0.4));
std::sort(std::begin(myVect), std::end(myVect));

Once the data is sorted, you could harvest the results into the original vectors.

like image 141
Sergey Kalinichenko Avatar answered Sep 16 '25 07:09

Sergey Kalinichenko


Is there more lazy way of doing this?

I think not.

I would one go with using std::pair, instead of a tuple.

like image 38
gsamaras Avatar answered Sep 16 '25 06:09

gsamaras