10.3.1 Passing a Function to an Algorithm
2025/9/22大约 2 分钟
10.3.1 Passing a Function to an Algorithm
- Predicates
- Sorting Algorithms
在顺序容器中存放有多个按照首字母排序的字符串,现在要求:
- 先按照单词的长度由小到大进行排列(第一个元素长度最小)
- 对于长度相同的单词,再按照其字母顺序排列
排序的对象:
vector<string> words = {"fox", "jumps", "over", "quick",
"red", "slow", "the", "turtle"};Predicates
[!quote]
A predicate is an expression that can be called and that returns a value that can be used as a condition. The predicates used by library algorithms are either unary predicates (meaning they have a single parameter) or binary predicates (meaning they have two parameters).
- can be called:可调用对象
- returns value 。。 condition:返回的值可以被转换为bool值
- library 中只有两种predicate:unary - 有1个参数;binary - 有两个参数
- 算法将element 当作predicate 的参数,通过predicate 的返回值进行判断。
- 由于算法传递element 给 predicate,所以要求element 的类型能够转换为predicate 的参数类型
使用排序算法比较字符串长度的predicate:
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}Sorting Algorithms
algorithms 与 使用的 predicate 类型表:
| algorithm | 参数 | predicate | 功能 |
|---|---|---|---|
| InputIt find_if | ( InputIt first, InputIt last, UnaryPred p ) | unary | find_if searches for an element for which predicate p returns true.返回使得predicate p 为真的元素的iterator |
| void stable_sort | ( RandomIt first, RandomIt last, Compare comp ); | binary | Sorts the elements in the range [first, last) in non-descending order. The order of equivalent elements is guaranteed to be preserved.按照不小于的顺序进行排列,对于相等值的元素,保持原有顺序 |
| void sort | ( RandomIt first, RandomIt last, Compare comp ); | binary | sort 也是按照 non-descending 的顺序排序,但是和stable_sort相比,它不保证相等值元素的顺序和排列前相同 |
因为words 已经是按照首字母顺序进行排列的了,所以只需要通过stable_sort()对其按照长度排序,相同长度的word 保持原有顺序(字母排列)。
实现:
std::stable_sort(words.begin(), words.end(), isShorter);
for(const auto &w : words)
cout << w << " ";
cout << endl;效果:
fox red the over slow jumps quick turtle