sort by the second element, and if those are equal, then sort by the first element

So, I have a vector of pair.

{2 , 3} { 3, 4} {5, 4} {7, 8}

I want to sort it based on the second element in descending order, so it should be this

{7 , 8} {3,4} {5, 4} {2 , 3}

But now, if the second element is equal to each other, I want the one with the larger element go first

So the {5, 4} need to go first

This is the code that I had tried, but it doesnt print anything

    sort(pai.begin(), pai.end(), sortByVal);
    long long temp1, temp2;
    for(int i = 0; i < pai.size(); i++)
    {
        for(int y = i ; y < pai.size();i++)
        {
            if(pai[i].second == pai[y].second && pai[i].first < pai[y].first)
            {
                temp1 = pai[i].first;
                temp2 = pai[i].second;
                pai[i].first = pai[y].first;
                pai[i].second = pai[y].second;
                pai[y].first = temp1;
                pai[y].second = temp2;
            }
        }

    }
    for(int i = 1; i < pai.size(); i++)
    {
        cout<<pai[i].first<<" ";
    }

Here is my function for sorting, I am thinking about making some changes in the return fuction but doesnt know exactly

bool sortByVal(const pair<long long, long long> &b, const pair<long long, long long> &c)
{
    return (b.second > c.second);
}

I am new to vector and pair so I doesn’t have much Idea how to do it, it would be appreciate if someone could help, thank!

>Solution :

You don’t need to sort twice, just put all of your sorting criteria into one function and use that.

sort(pai.begin(), pai.end(), sortByVal);
for(int i = 1; i < pai.size(); i++)
{
    cout<<pai[i].first<<" ";
}

bool sortByVal(const pair<long long, long long> &b, const pair<long long, long long> &c)
{
    return (b.second > c.second) || (b.second == c.second && b.first > c.first);
}

Leave a Reply