本文选自:祁宇. 深入应用C++11:代码优化与工程级应用. 北京:机械工业出版社,2015.5
有改动。
算法库新增了3个用于判断的算法 all_of、any_of 和 none_of:
template<class _InIt, class _Pr>
bool all_of(_InIt _First, _InIt _Last, _Pr _Pred);
template<class _InIt, class _Pr>
bool none_of(_InIt _First, _InIt _Last, _Pr _Pred);
template<class _InIt, class _Pr>
bool any_of(_InIt _First, _InIt _Last, _Pr _Pred);
其中:
all_of 检查区间 [ _First, _Last ) 中是否所有元素都满足一元判断式 _Pr。
any_of 检查区间 [ _First, _Last ) 中是否存在一个元素满足一元判断式 _Pr。
none_of 检查区间 [ _First, _Last ) 中是否所有元素都不满足一元判断式 _Pr。
下面是它们的例子:
#include <algorithm>
#include <iostream>
#include <vector>
auto IsOdd(int n) -> bool
{
return n % 2 != 0;
}
int main()
{
std::vector<int> v0{ 1,3,5,7,9 };
std::vector<int> v1{ 2,3,6,7,89,100 };
std::vector<int> v2{ 2,4,46,80,8 };
if (std::all_of(v0.begin(), v0.end(), ::IsOdd))
{
std::cout << "都是奇数。" << std::endl;
}
if (std::any_of(v1.begin(), v1.end(), ::IsOdd))
{
std::cout << "有奇数。" << std::endl;
}
if (std::none_of(v2.begin(), v2.end(), ::IsOdd))
{
std::cout << "没有奇数。" << std::endl;
}
return 0;
}