读书人

Stable_sort 谓词解决思路

发布时间: 2012-08-15 16:57:17 作者: rapoo

Stable_sort 谓词
在c++primer 346页书中说 调用Stable_sort后,word中的元素按照长度大小排序,而长度相同的单词则按照字典顺序排列。。
stable_sort(word.begin(),word.end(),isShorter); 其中isShorter是这样定义的
bool isShorter(const string &s1,const string &s2)
{
return s1.size()<s2.size();
}
似乎这样并不能把长度相等的按照字典序排列吧?
请问如果要实现他说的功能谓词该怎么写?

[解决办法]
下面那样写,就可以做到楼主说的那种要求。

C/C++ code
#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace std;bool isShorter(const string& s1, const string& s2){    if(s1.size() == s2.size())    {        return s1 < s2;    }    return s1.size() < s2.size();}int main(){    vector<string> word;    word.push_back("cccc");    word.push_back("bbb");    word.push_back("aaa");        stable_sort(word.begin(), word.end(), isShorter);    for(vector<string>::iterator iter = word.begin(); iter != word.end(); ++iter)    {        cout << *iter << endl;    }    return 0;} 

读书人网 >C++

热点推荐