简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM