简体   繁体   English

用字符串和整数对排序矢量

[英]Sort Vector with string and int pair

cmp 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 . 我正在尝试根据对的second元素pair vector进行排序。 If the second elements of the pair are equal, then I compare the first elements of the pair . 如果second对对元素相等,那么我比较first所述的元件pair

I'm using the above code to sort a vector containing string and int pair . 我正在使用上面的代码对包含stringint pairvector进行排序。 I'm invoking the sorting function using sort_heap(vector.begin(),vector.end(),cmp); 我正在使用sort_heap(vector.begin(),vector.end(),cmp);调用排序函数sort_heap(vector.begin(),vector.end(),cmp); . But this doesn't seem to work as expected. 但这似乎没有按预期工作。

Just use operator< for the strings: 只需使用operator<作为字符串:

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. strcmp返回一个负数,如果第一个是“小于”第二个(这就是你所关心的),如果它们相等则返回0,如果第二个小于第一个,则返回正数。 So, if you wanted to use strcmp, you would do it like this: 所以,如果你想使用strcmp,你会这样做:

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

But I don't see why you would do that. 但我不明白为什么你会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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