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?
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.
Is there more lazy way of doing this?
I think not.
I would one go with using std::pair
, instead of a tuple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With