//函数原型
// TEMPLATE FUNCTION find_if
template<class _InIt,class _Pr> inline
_InIt _Find_if(_InIt _First, _InIt _Last, _Pr _Pred)
{
// find first satisfying _Pred
for (; _First != _Last; ++_First)
if (_Pred(*_First))
break;
return (_First);
}
template<class _InIt,class _Pr> inline
_InIt find_if(_InIt _First, _InIt _Last, _Pr _Pred)
{
// find first satisfying _Pred
_DEBUG_RANGE(_First, _Last);
_DEBUG_POINTER(_Pred);
return (_Rechecked(_First,_Find_if(_Unchecked(_First), _Unchecked(_Last), _Pred)));
}
使用例(STL LIST容器):
#include <iostream>
#include <stdio.h>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class keyValue
{
//private:
public:
string m_key;
string m_value;
public:
keyValue():m_key(""),m_value(""){}
keyValue(string key, string value = ""):m_key(key), m_value(value){}
bool operator () (const keyValue &temp)// ()重载
{
return m_key == temp.m_key;
}
};
int main(int argc, char *argv[])
{
list<keyValue> test;
test.push_back(keyValue("a", "1"));
test.push_back(keyValue("b", "2"));
test.push_back(keyValue("c", "3"));
list<keyValue>::iterator iter = find_if(test.begin(), test.end(), keyValue("b"));
if(iter != test.end())//如果迭代器指向end代表没查到
{
cout << "find successful" << endl;
cout << iter->m_key << endl;
cout << iter->m_value << endl;
test.erase(iter);//删除
}
else
cout << "find failed" << endl;
iter = find_if(test.begin(), test.end(), keyValue("b"));
if(iter != test.end())
{
cout << "find successful" << endl;
cout << iter->m_key << endl;
cout << iter->m_value << endl;
test.erase(iter);
}
else
cout << "find failed" << endl;
system("pause");
return 0;
}
运行结果: