在 STL 的 algorithm 头文件中定义了 3 种算法,用来检查在算法应用到序列中的元素上时,什么时候使谓词返回 true。any_of() 算法会返回 true,前提是序列中的任意一个元素都可以使谓词返回 true。
#include <algorithm>
template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
参数 | 描述 |
---|---|
first | 输入迭代器 |
last | 输入迭代器 |
pred | 自定义比较规则 |
first, last 标示序列范围的输入迭代器。包括 first 指向的元素,但不包括 last。
pred 一个接受一个元素类型参数并返回一个 bool 值的一元函数。可以是一个指针或者函数对象。
如果范围内任一元素使 pred 返回 true,则返回 true,否则返回 false.
使用 STL any_of 函数判断集合
#include <iostream>
#include <algorithm>
using namespace std;
bool isGreat(int i)
{
if(i >= 5)
{
return true;
}
else
{
return false;
}
}
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
vector<int> vi{0, 1, 2, 3, 4, 5, 6};
if(any_of(vi.begin(), vi.end(), isGreat))
{
cout << "Yes,some elements in vi >=5 " << endl;
}
else
{
cout << "no,all elements in vi didn't >=1 " << endl;
}
cout<<endl;
int ar[5] = {10, 20, 30, 40, 50};
if(any_of(ar, ar+5, [](int i){return i%10;}))
{
cout << "some in ar can %10 != 0" << endl;
}
else
{
cout << "all %10 = 0!" << endl;
}
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ any_of.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
any_of 函数会判断所有的元素只要有一个符合要求,才会返回 true。
使用 STL any_of 函数判断集合
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
std::array<int,7> foo = {0, 1, -1, 3, -3, 5, -5};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
{
std::cout << "There are negative elements in the range.\n";
}
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ any_of.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
any_of 函数会判断所有的元素只要有一个符合要求,才会返回 true。
在 STL 的 algorithm 头文件中定义了 3 种算法,用来检查在算法应用到序列中的元素上时,什么时候使谓词返回 true。any_of() 算法会返回 true,前提是序列中的任意一个元素都可以使谓词返回 true。