如何使用STL进行查找?通用算法find()和find_if()可以做这些。就象for_each(), count(), count_if()一样,这些算法也使用iterator范围,这个范围指出一个list或任意其他容器中的一部分来处理。通常首iterator指着开始的位置,次iterator指着停止处理的地方。由次iterator指出的元素不被处理。
这是find()如何工作:
/*
|| How to find things in an STL list
*/
#include<string>
#include <list>
#include <algorithm>
int main (void){
list<string> Fruit;
list<string>::iterator FruitIterator;
Fruit.push_back("Apple");
Fruit.push_back("Pineapple");
Fruit.push_back("Star Apple");
FruitIterator = find (Fruit.begin(), Fruit.end(),"Pineapple");
if (FruitIterator == Fruit.end()) {
cout << "Fruit not found in list" << endl;
}
else {
cout<< *FruitIterator <<endl;
}
}
输出是:
Pineapple
如果没有找到指出的对象,就会返回Fruit.end()的值,要是找到了就返回一个指着找到的对象的iterator。
以上是针对简单数据类型的查找,如string,int, char, double,float等,如果你想用一个自定义类型的数据作为查找依据该怎么做呢。
例如有这样的数据结构:
structMyType
{
int a,b;
}
MyType* mt;
mt = new MyType;
mt->a = 1;
mt->b = 2;
list<MyType> mList;
find(mList.begin(), mList.end(), *mt);
这里find函数是不能完成查询的,最简单的原因就是它无法知道通过对比MyType的哪项完成查询。
find的查找本质上还是比较,所以只需要重载一个==操作符即可。
即
bool operator==(const MyType &object)
{
return object.a == a && object.b == b;
}
此外,另一种是写一个查找条件函数,利用find_if()。
假如需要根据a或b一项来查询,则需要定义个构造函数及修改下==操作符。
例如需要根据a来查询:
structMyType
{
int a,b;
// 定义默认构造函数
MyType(int a)
: a(a)
{}
bool operator==(const MyType &object)
{
return object.a == a;
}
}
这也就可以使用find(mList.begin(), mList.end(), MyType(1));来查找是否存在a = 1的项了