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

8
  • 3
    Recommended read: Why should I not #include <bits/stdc++.h>? Why is “using namespace std;” considered bad practice? Commented Apr 19, 2020 at 10:50
  • 2
    tuples already have a operator< Commented Apr 19, 2020 at 10:50
  • can you please clarify if one line missing from your output is just a typo here, or really the output you see? Commented Apr 19, 2020 at 11:01
  • @idclev463035818 Pls ignore cout << "Printing range sorted queries" << endl; printing. Point is to get the sorted output of ranges. Commented Apr 19, 2020 at 11:06
  • @user3243499 I didnt even notice that line, but your acual output is 5 entries, and expected is 6 Commented Apr 19, 2020 at 11:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.