您的位置:首页 > 编程语言 > C语言/C++

C++ find_if函数使用(STL_LIST)

2015-12-22 15:25 736 查看
//函数原型
// 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;
}
运行结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C C++ find_if STL LIST