find_if (STL Samples)
在 Visual C++ 演示如何使用 find_if 标准 (STL)模板库函数。
template<class InputIterator, class T, class Predicate> inline
InputIterator find_if(
InputIterator First,
InputIterator Last,
Predicate Predicate
)
备注
备注
类/参数名在原型不匹配版本在头文件。修改某些提高可读性。
find_if 算法将第一个元素针对的范围 [First, Last) 原因谓词为其返回 true 并返回迭代器确定该组件或 Last ,如果未找到这样的元素。
示例
// findif.cpp
// compile with: /EHsc
// disable warning C4786: symbol greater than 255 characters,
// okay to ignore
#pragma warning(disable: 4786)
#include <algorithm>
#include <iostream>
using namespace std;
// returns true if n is an odd number
int IsOdd( int n)
{
return n % 2 ;
}
int main()
{
const int ARRAY_SIZE = 8 ;
int IntArray[ARRAY_SIZE] = { 1, 2, 3, 4, 4, 5, 6, 7 } ;
int *location ; // stores the position of the first
// element that is an odd number
int i ;
// print content of IntArray
cout << "IntArray { " ;
for(i = 0; i < ARRAY_SIZE; i++)
cout << IntArray[i] << ", " ;
cout << " }" << endl ;
// Find the first element in the range [first, last -1 ]
// that is an odd number
location = find_if(IntArray, IntArray + ARRAY_SIZE, IsOdd) ;
// print the location of the first element
// that is an odd number
if (location != IntArray + ARRAY_SIZE) // first odd element found
cout << "First odd element " << *location
<< " is at location " << location - IntArray << endl;
else // no odd numbers in the range
cout << "The sequence does not contain any odd numbers"
<< endl ;
}
Output
IntArray { 1, 2, 3, 4, 4, 5, 6, 7, }
First odd element 1 is at location 0
要求
**标题:**algorithm