C++ 算法库提供的操作是不依赖容器类型的,可以作用在不同类型的容器和不同类型的元素上,是“泛型”的
C++算法库提供的算法不依赖容器的操作,只单独依赖迭代器和迭代器操作的实现。
大多数情况下,算法都需要两个迭代器来指出该算法操纵的元素范围
C++ 算法库主要包含以下操作:
1. Non-modifying sequence operations(不修改序列内容的操作)
1.1 checks if a predicate is true for all, any or none of the elements in a range
在头文件
<algorithm> 中定义
| ||
template<class InputIt,class UnaryPredicate> bool all_of( InputIt first, InputIt last, UnaryPredicate p); | (1) | (C++11 起) |
template<class InputIt,class UnaryPredicate> bool any_of( InputIt first, InputIt last, UnaryPredicate p); | (2) | (C++11 起) |
template<class InputIt,class UnaryPredicate> bool none_of( InputIt first, InputIt last, UnaryPredicate p); |
all_of //first 和last 之间的所有元素都使得 P返回true 时 返回true
any_of //first 和last 之间的一个或多个元素都使得 P返回true 时 返回true
none_of //first 和last 之间的没有元素都使得 P返回true 时 返回true
1.2 applies a function to a range of elements
Defined in header
<algorithm>
| ||
template<class InputIt, class UnaryFunction> UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f); |
for_each //对迭代器范围类的所有元素进行函数f 的操作
|
1.3 returns the number of elements satisfying specific criteria
Defined in header
<algorithm>
| ||
template<class InputIt, class T > typename iterator_traits<InputIt>::difference_type | (1) | |
template<class InputIt, class UnaryPredicate> typename iterator_traits<InputIt>::difference_type |
count // 计算迭代器范围内T出现的次数
count_if //计算迭代器范围类使P 返回true 的元素个数
1.3 finds the first position where two ranges differ
Defined in header
<algorithm>
| ||
template<class InputIt1, class InputIt2 > std::pair<InputIt1,InputIt2> | (1) | |
template<class InputIt1, class InputIt2,class BinaryPredicate > std::pair<InputIt1,InputIt2> | (2) | |
template<class InputIt1, class InputIt2 > std::pair<InputIt1,InputIt2> | (3) | (since C++14) |
template<class InputIt1, class InputIt2,class BinaryPredicate > std::pair<InputIt1,InputIt2> | (4) | (since C++14) |
Returns the first mismatching pair of elements from two ranges: one defined by[first1, last1)
and another defined by [first2,last2)
. Iflast2
is not provided (overloads (1,2)), it denotesfirst2 + (last1 - first1)
.
Overloads (1,3) use operator==
to compare the elements, overloads(2,4) use the given binary predicate p
.
mismatch // 返回两个迭代器范围内第一个不相等元素的pair
//待补充