0

I have a vector of tuples which I want to sort first w.r.t. 1st value, then w.r.t. 2nd value.

Here is the code used:

#include <bits/stdc++.h>
using namespace std;

bool mysort(const tuple<int, int, int>& a, const tuple<int, int, int>& b) {
    if (get<0>(a) < get<0>(b)) {
        if (get<1>(a) > get<1>(b)) return false;
        else return true;
    }
    else return false;
}

int main() {
    vector<tuple<int, int, int>> queries;
    int n;
    cin >> n;

    for(int i = 0; i<n; i++) {
        int l, r, c;
        cin >> l >> r;

        queries.push_back(make_tuple(l, r, i));
    }
    sort(queries.begin(), queries.end(), mysort);

    // print sorted queries

    for (int i = 0; i < queries.size(); i++) {
        cout << get<0>(queries[i]) << ", " << get<1>(queries[i]) << endl;
    }
    return 0;
}

Input used:

6
1 2
1 5
1 3
2 8
3 3
5 8

Output from above code:

1, 2
1, 5
1, 3
2, 8
3, 3
5, 8

Expected sorted output is:

1, 2
1, 3
1, 5
2, 8
3, 3
5, 8

Issue reproducible link: https://ideone.com/4iVJuD

user3243499
  • 2,953
  • 6
  • 33
  • 75

1 Answers1

1

Your problem is in mysort function. If the first element of the comparing tuples is equal, you just say the second tuple is less. Consider the following code:

bool mysort(const tuple<int, int, int>& a, const tuple<int, int, int>& b) {
    if (get<0>(a) < get<0>(b)) return true;
    if (get<0>(a) > get<0>(b)) return false;
    if (get<1>(a) < get<1>(b)) return true; // Here the first element is equal
    return false;
}

This would result in the expected output.

amirali
  • 1,888
  • 1
  • 11
  • 32