MSDN上的解释:
any_of
Visual Studio 2010
Returns true when a condition is present at least once in the specified range of elements.
template<class InputIterator, class UnaryPredicate> bool any_of( InputIterator _First, InputIterator _Last, UnaryPredicate _Comp );
- _First
-
An input iterator that indicates where to start checking a range of elements for a condition. - _Last
-
An input iterator that indicates the end of the range of elements to check for a condition. - _Comp
-
A condition to test for. This is provided by a user-defined predicate function object. The predicate defines the condition to be satisfied by the element being tested. A predicate takes a single argument and returns true or false.
Returns true if the condition is detected at least once in the indicated range, false if the condition is never detected.
The template function returns true only if, for some N in the range
[0, _Last - _First), the predicate _Comp(*(_First + N)) is true.
Header: <algorithm>
Namespace: std
any_of与all_of类似,不同点在于,all_of是所有元素都满足条件才返回true。any_of是只要有一个元素满足条件就返回true。
程序示例如下:
// any_of.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <algorithm> #include <vector> #include <iostream> using namespace std; bool IsOdd( int elem ) { if( elem%2 != 0) return true; else return false; } int _tmain(int argc, _TCHAR* argv[]) { vector<int> v1(5); vector<int>::size_type i; for( i=0 ; i<5; i++) { v1[i] = i; } if( any_of( v1.begin( ), v1.end( ), IsOdd ) ) cout << " all the elements int the vector v1 are odd! " << endl; else cout << " not all the elements int the vector v1 are odd! " << endl; vector<int> v2(5); for(vector<int>::iterator iter = v2.begin() ; iter != v2.end(); ++iter) { *iter = 2; } if( any_of( v2.begin( ), v2.end( ), IsOdd ) ) cout << " all the elements int the vector v2 are odd! " << endl; else cout << " not all the elements int the vector v2 are odd! " << endl; system("pause"); }
程序运行结果如下:
时间: 2024-10-06 16:32:35