Srinath G S
Srinath G S

Reputation: 155

Sort Vector with string and int pair

cmp

bool cmp(const pair<string, long> &p1, const pair<string, long> &p2){
if(p1.second!=p2.second)
return p1.second < p2.second;
return strcmp(p1.first.c_str(),p2.first.c_str()); }

Hi all,

I'm trying to sort the vector based on the second element of the pair. If the second elements of the pair are equal, then I compare the first elements of the pair.

I'm using the above code to sort a vector containing string and int pair. I'm invoking the sorting function using sort_heap(vector.begin(),vector.end(),cmp);. But this doesn't seem to work as expected.

Upvotes: 3

Views: 3011

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

Just use operator< for the strings:

bool cmp(const pair<string, long> &p1, const pair<string, long> &p2)
{
    if(p1.second!=p2.second)
        return p1.second < p2.second;
    return p1.first < p2.first;
}

strcmp returns a negative number if the first is "less than" the second (and that's all you care about), 0 if they are equal, and a positive number if the second is less than the first. So, if you wanted to use strcmp, you would do it like this:

return strcmp(p1.first.c_str(), p2.first.c_str()) < 0;

But I don't see why you would do that.

Upvotes: 8

Related Questions