Algorithm学习之all_of学习
all_of
Visual Studio 2010
Returns true when a condition is present at each element in the given range.
当所有在指定的范围内所有元素都满足指定条件的时候返回true。
template<class InputIterator, class Predicate> bool all_of( InputIterator _First, InputIterator _Last, BinaryPredicate _Comp );
Returns true if the condition is detected at each element in the indicated range, and false if the condition is not detected at least one time.
当指定范围内所有元素都满足条件时就返回true,当有至少一个元素不满足条件时返回false。
The template function returns true only if, for each N in the range [0, _Last - _First), the predicate _Comp(*(_First + N)) is true.
模板函数只有当对于范围内的N个数都满足给定条件的时候返回true。
Header: <algorithm>
Namespace: std
程序示例:
1 // all_of.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <algorithm> 6 #include <list> 7 #include <iostream> 8 #include <vector> 9 using namespace std; 10 11 bool IsEven( int elem ) 12 { 13 if( elem%2 == 0 ) 14 return true; 15 else 16 return false; 17 } 18 19 int _tmain(int argc, _TCHAR* argv[]) 20 { 21 22 list <int> L; 23 24 L.push_back(2); 25 L.push_back(4); 26 L.push_back(6); 27 L.push_back(8); 28 L.push_back(10); 29 30 if( all_of( L.begin(), L.end(), IsEven ) ) 31 cout << " Yes,all the elements in the list are even! " << endl; 32 else 33 cout << " No,some of the elements in the list are not even! " << endl; 34 35 int arr1[5] = {1,2,4,6,8}; 36 vector<int> v1(arr1,arr1+5); 37 if( all_of( v1.begin( ), v1.end( ), IsEven ) ) 38 cout << " Yes,all the elements in the vector are even! " << endl; 39 else 40 cout << " No,some of the elements in the vector are not even! " << endl; 41 42 int arr[5] = {1,2,3,4,5}; 43 if( all_of( arr, arr+5, IsEven ) ) 44 cout << " Yes,all the elements in the array are even! " << endl; 45 else 46 cout << " No,some of the elements in the array are not even! " << endl; 47 48 system("pause"); 49 }
程序运行结果截图: