使用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;
}
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;
};
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);
}
// 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;
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;
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);
}
return (a -> Name() == b -> Name() && a -> Value() == b -> Value());
}
bool operator == ( const Inst * a, const string nm){
return (a -> Name() == nm);
}
在学习STL过程中,如果有错误的地方,还请各位指正,谢谢!