默认情况下,算法都是使用元素类型的 < 或==运算符完成比较。
标准库还未这些算法定义了额外版本,允许我们提供自定义的操作来代替默认运算符。
向算法传递函数
// 比较函数,用来按长度排序单词bool isShorter(const string &s1,const string &s2){return s1.size() < s2.size();}// 按长度由短至长排序wordssort(words.begin(),words.end(),isShorter);
stable_sort算法
在将words按大小重排的同时,还希望具有相同长度的元素按字典序排列。为了保持相同长度的单词按字典序排列,可以用stable_sort算法。
elimDups(words); // 将words按字典序重排,并消除重复单词// 按长度重新排序,长度相同的单词维持字典序stable_sort(words.begin(),words.end(),isShorter);for(const auto &s: words) // 无须拷贝字符串{cout << s << " ";}cout << endl;
如果用原来的vector内容运行这段代码,输出为:
fox red the over slow jumps quick turtle
