0

Suppose I want to sort vector A,B and C based on vector A in the ascending order, such that vector B and C will change accordingly. If vector A contains two or more same elements, then priority will be given to larger value on corresponding vector C. Take an example.

A=25,10,10,5,5

B=12,14,3,45,6

C=123,23,12,45,76

After sorting it would look like this

A=5,5,10,10,15

B=6,45,14,3,12

C=76,45,23,12,123

Can anyone tell how to write a c++ program for that ?which library can be use for this?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • `A=25,10,10,5,5` -- What if the `10` or `5` are not in consecutive positions? How will you know which `10` or which `5` is being used in the sorting criteria? – PaulMcKenzie May 20 '20 at 07:19
  • 1
    Generally when I see problems asking about sorting one container, and having the ordering of a second (or third!) container change according to that sort, that usually indicates that you need a single container of a complex datatype such as `std::vector` or `std::vector>` – JohnFilleau May 20 '20 at 07:22
  • @PaulMcKenzie We can then check corresponding value of C . it means that 2nd element of vector A linked to 2nd element of vector B and C . Similarly 3rd element of vector B related to 3rd element of vector B and C –  May 20 '20 at 07:23
  • Can anyone help me to understand by taking my example and prove it using a c++ program? –  May 20 '20 at 07:24
  • @JohnFilleau can u help me to understand by taking my given example using a c++ program? –  May 20 '20 at 07:25
  • 1
    Which part don't you understand? Making a custom datatype, or sorting on that datatype according to your stated rules? The method I'm proposing would require a struct and a custom compare operation. – JohnFilleau May 20 '20 at 07:28
  • here's a Q/A about sorting a vector of custom datatypes: https://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects – JohnFilleau May 20 '20 at 07:29

1 Answers1

1

With range-v3, you might use zip view:

std::vector A = {25,10,10,5,5};
std::vector B = {12,14,3,45,6};
std::vector C = {123,23,12,45,76};
auto r = ranges::view::zip(A, B, C);
ranges::sort(r,
             std::less<>{},
             [](const auto& tup){
                 return std::make_tuple(std::get<0>(tup), -std::get<2>(tup));
             });

Demo

(instead of "cheating" with projection and negate C value, you might create custom comparer)

Jarod42
  • 203,559
  • 14
  • 181
  • 302