3

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?

lee
  • 740
  • 2
  • 11
  • 24
  • 1
    `std::map` is ordered by `key`. – George Aug 18 '18 at 16:44
  • 1
    Use a third vector with Indices and sort it with a comparator function dereferencing the Index and comparing the numbers in a. – sim Aug 18 '18 at 16:46
  • 1
    Following up with @sim's comment, after sorting the vector of indexes according to one of the vectors, the vectors can the be reordered according to the sorted vector of indexes in place and with O(n) time complexity as shown in [this example](https://stackoverflow.com/questions/44027808/sorting-two-arrays-based-on-one-with-standard-library-copy-steps-avoided/44030600#44030600) . – rcgldr Aug 18 '18 at 20:04

2 Answers2

2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Is there more lazy way of doing this?

I think not.

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305