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.
Just use
operator<for the strings: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:
But I don’t see why you would do that.