简单的程序诠释C++ STL算法系列: find & find_if

来源:互联网 发布:java math.random 编辑:程序博客网 时间:2024/05/19 05:02

find算法用于查找等于某值的元素。它在迭代器区间[first , last)上查找等于value值的元素,如果迭代器iter所指的元素满足 *iter == value ,则返回迭代器iter,未找则返回last。

函数原型:

[cpp] view plaincopy
  1. template<class InputIterator, class Type>  
  2.    InputIterator find(  
  3.       InputIterator _First,   
  4.       InputIterator _Last,   
  5.       const Type& _Val  
  6.    );  

示例代码:

[cpp] view plaincop
  1.   
  2. #include <algorithm>  
  3. #include <list>  
  4. #include <iostream>  
  5.   
  6. using namespace std;  
  7.   
  8. int main()  
  9. {  
  10.     list<int> ilist;  
  11.     for (size_t i = 0; i < 10; ++i)  
  12.     {  
  13.         ilist.push_back(i+1);  
  14.     }  
  15.   
  16.     ilist.push_back(10);  
  17.   
  18.     list<int>::iterator iLocation = find(ilist.begin(), ilist.end(), 10);  
  19.   
  20.     if (iLocation != ilist.end())  
  21.     {  
  22.         cout << "找到元素 10" << endl;  
  23.     }  
  24.   
  25.     cout << "前一个元素为:" << *(--iLocation) << endl;  
  26.   
  27.     return 0;  
  28. }  


/********************************************************************

    created:    2013/08/31   15:20
    Filename:   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;
}
原创粉丝点击