STL(1)——查找函数find的使用

使用list, vector 等这些标准库的类,查找是比较常用的功能,但是这些类没有提供find函数,因为对于自定义类型,它不知道如何去比较两个类型。

http://www.cppreference.com/wiki/container/list/start

但是STL提供了一种通用的查找函数find(iterator it0,iterator it1,target),下面介绍如何使用这个查找函数。

// 定义一个简单的数据结构Inst.
class Inst{
public :
Inst(
string nm, int val){
name
= nm;
value
= val;
}
// 之前这里有个分号,并不应该出现的,谢谢提醒
string Name() const {
return name;
}
int Value() const {
return value;
}
  
private :
string name;
int value;
};
// 定义比较函数,重载==运算符。
// name 和 value 都一样, 则 实例一样
bool operator == ( const Inst & a, const Inst & b){
return (a.Name() == b.Name() && a.Value() == b.Value());
}

// name 一样, 则 实例一样
bool operator == ( const Inst & a, const string name){
return (a.Name() == name);
}

测试如下,

list < Inst > elist;
Inst p1(
" abc " , 3 );
Inst p2(
" abcdef " , 6 );

list
< Inst > ::iterator it;
// find 需要包含头文件 <algorithm>
it = std::find(elist.begin(),elist.end(),p2);
if (it != elist.end())
cout
<< ( * it).Value() << endl;
string name = " abc " ;
it
= std::find(elist.begin(),elist.end(),name);
if (it != elist.end())
cout
<< ( * it).Value() << endl;

但是如果list保存指针,如下,

list < Inst *> elist;
Inst
* p1 = new Inst( " abc " , 3 );
Inst
* p2 = New Inst( " abcdef " , 6 );
list
< Inst *> ::iterator it;
it
= std::find(elist.begin(),elist.end(),p2);
if (it != elist.end())
cout
<< ( * it) -> Value() << endl;
string name = " abc " ;
it
= std::find(elist.begin(),elist.end(),name);
if (it != elist.end())
cout
<< ( * it) -> Value() << endl;

那么比较函数就需要做一些修改,如下,

bool operator == ( const Inst * a, const Inst * b){
return (a -> Name() == b -> Name() && a -> Value() == b -> Value());
}
bool operator == ( const Inst * a, const string nm){
return (a -> Name() == nm);
}

在学习STL过程中,如果有错误的地方,还请各位指正,谢谢!

转载于:https://www.cnblogs.com/Frandy/archive/2011/06/03/STL_Find_List.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值