Блог пользователя I_am_Heisenberg

Автор I_am_Heisenberg, история, 6 лет назад, По-английски

Hi! Suppose, I have several integer elements like this:

(3 9 1), (1 5 2), (2 8 3), (1 4 4), (1 6 5), (1 5 6).

Now I want to sort the elements like vector of pairs are sorted. Only difference is that instead of 2 keys we have 3 keys here. After sorting the elements will look like:

(1 4 4), (1 5 2), (1 5 6), (1 6 5), (2 8 3), (3 9 1).

Is there any STL or other techniques to achieve this? I found out about "Tuples" but having some problems to understand this well. Can you guys help me in any way please? May be by providing useful links or Explaining the process.

Thanks.. :)

UPD: I got my ans here: https://stackoverflow.com/a/50106878/6928946

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
6 лет назад, # |
  Проголосовать: нравится +27 Проголосовать: не нравится

vector<array<int,3>> vec;

sort(vec.begin(), vec.end());

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by I_am_Heisenberg (previous revision, new revision, compare).

»
6 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Write your own comparator function.

»
6 лет назад, # |
Rev. 2   Проголосовать: нравится +6 Проголосовать: не нравится

C++11 support tuple

For example:

vector<tuple<int, char, bool> > a;
int x = 1;
char y = 'a';
bool z = true;
a.push_back(make_tuple(x, y, z));

Of course you can sort vector of tuple like vector of pair:

sort(a.begin(), a.end());

To get the i-th element of a tuple, you can do like this,

int x = get<0>(a[0]) // first element of tuple a[0]
char y = get<1>(a[0]) // second element

or you can get all elements at the same time like this:

int x;
char y;
bool z;
tie(x, y, z) = a[0];

Remember it only works with C++11.

You can find more here

  • »
    »
    6 лет назад, # ^ |
      Проголосовать: нравится +5 Проголосовать: не нравится

    Thanks a lot. Your comment was very helpful. However I solved my problem. Actually it was a problem I faced yesterday at Educational CF round..