默认情况下,算法都是使用元素类型的 < 或==运算符完成比较。
标准库还未这些算法定义了额外版本,允许我们提供自定义的操作来代替默认运算符。

向算法传递函数

  1. // 比较函数,用来按长度排序单词
  2. bool isShorter(const string &s1,const string &s2)
  3. {
  4. return s1.size() < s2.size();
  5. }
  6. // 按长度由短至长排序words
  7. sort(words.begin(),words.end(),isShorter);

stable_sort算法

在将words按大小重排的同时,还希望具有相同长度的元素按字典序排列。为了保持相同长度的单词按字典序排列,可以用stable_sort算法。

  1. elimDups(words); // 将words按字典序重排,并消除重复单词
  2. // 按长度重新排序,长度相同的单词维持字典序
  3. stable_sort(words.begin(),words.end(),isShorter);
  4. for(const auto &s: words) // 无须拷贝字符串
  5. {
  6. cout << s << " ";
  7. }
  8. cout << endl;

如果用原来的vector内容运行这段代码,输出为:
fox red the over slow jumps quick turtle