Algorithm学习之any_of
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 );
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"); }
程序运行结果如下: