簡單的程序詮釋C++ STL算法系列之三:find_if

      C++STL的非變易算法(Non-mutating algorithms)是一組不破壞操作數據的模板函數,用來對序列數據進行逐個處理、元素查找、子序列搜索、統計和匹配。

     find_if算法 是find的一個謂詞判斷版本,它利用返回布爾值的謂詞判斷pred,檢查迭代器區間[first, last)上的每一個元素,如果迭代器iter滿足pred(*iter) == true,表示找到元素並返回迭代器值iter;未找到元素,則返回last。

    函數原型:

template<class InputIterator, class Predicate>
   InputIterator find_if(
      InputIterator _First, 
      InputIterator _Last, 
      Predicate _Pred
   );


    示例代碼:

/*******************************************************************
 * Copyright (C) Jerry Jiang              
 * File Name   : find_if.cpp
 * Author      : Jerry Jiang
 * Create Time : 2011-9-29 22:21:29
 * Mail        : [email protected]
 * Blog        : http://blog.csdn.net/jerryjbiao               
 * Description : 簡單的程序詮釋C++ STL算法系列之三              
 *               非變易算法 : 條件查找容器元素find_if               
 ******************************************************************/

#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

//謂詞判斷函數 divbyfive : 判斷x是否能5整除
bool divbyfive(int x)
{
	return x % 5 ? 0 : 1;
}

int main()
{
	//初始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
	}
	
	return 0;
}

*******************************************************************************************************************************

C++經典書目索引及資源下載:http://blog.csdn.net/jerryjbiao/article/details/7358796

******************************************************************************************************************************** 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章