template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
若區間 [first, last) 中任意元素滿足一元謂詞 pred(即 pred(elem) == true),返回 true;否則返回 false。空區間直接返回 false。
template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred) {
while (first != last) {
if (pred(*first)) return true;
++first;
}
return false;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isGreat(int i) {
if (i >= 5) {
cout << i << " >= 5, match!" << endl;
return true;
}
return false;
}
int main() {
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 << "all elements in vi < 5" << endl;
return 0;
}
輸出:
5 >= 5, match! 6 >= 5, match! yes, some elements in vi >= 5
vector<int> vi = {0,1,2,3,4,5,6};
if (any_of(vi.begin(), vi.begin(), isGreat))
cout << "emptiy = true" << endl;
else
cout << "emptiy = false" << endl;
// 輸出: emptiy = false
vector<int> v = {1, 3, 5, 7, 9};
bool hasEven = any_of(v.begin(), v.end(), [](int x){ return x % 2 == 0; });
// hasEven == false
<algorithm> (C++11 起)。