find算法用于查找等于某值的元素。它在迭代器区间[first , last)上查找等于value值的元素,如果迭代器iter所指的元素满足 *iter == value ,则返回迭代器iter,未找则返回last。
函数原型:
- template<class InputIterator, class Type>
- InputIterator find(
- InputIterator _First,
- InputIterator _Last,
- const Type& _Val
- );
示例代码:
- #include <algorithm>
- #include <list>
- #include <iostream>
- using namespace std;
- int main()
- {
- list<int> ilist;
- for (size_t i = 0; i < 10; ++i)
- {
- ilist.push_back(i+1);
- }
- ilist.push_back(10);
- list<int>::iterator iLocation = find(ilist.begin(), ilist.end(), 10);
- if (iLocation != ilist.end())
- {
- cout << "找到元素 10" << endl;
- }
- cout << "前一个元素为:" << *(--iLocation) << endl;
- return 0;
- }
/********************************************************************
created: 2013/08/31 15:20Filename: pro23.cpp
author: Neo
*********************************************************************/
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
//谓词判断函数 divbyfive : 判断x是否能5整除
bool divbyfive(int x)
{
return x % 5 ? 0 : 1;
}
int main()
{
bool bT = divbyfive(15);
//初始vector
vector<int> iVect(20);
for(size_t i = 0; i < iVect.size(); ++i)
{
iVect[i] = (i+1) * (i+3);
}
vector<int>::iterator iLocation;
iLocation = find_if(iVect.begin(), iVect.end(), divbyfive);
if (iLocation != iVect.end())
{
cout << "第一个能被5整除的元素为:"
<< *iLocation << endl //打印元素:15
<< "元素的索引位置为:"
<< iLocation - iVect.begin() << endl; //打印索引位置:2
}
getchar();
return 0;
}