STL的find,find_if函数提供了一种对数组、STL容器进行查找的方法。使用该函数,需 #include <algorithm>
我们查找一个list中的数据,通常用find(),例如:
文章来源:http://www.codelast.com/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
using
namespace
std;
int
main()
{
list< int >
lst;
lst.push_back(10);
lst.push_back(20);
lst.push_back(30);
list< int >::iterator
it = find(lst.begin(), lst.end(), 10); //
查找list中是否有元素“10”
if
(it != lst.end()) //
找到了
{
//
do something
}
else
// 没找到
{
//
do something
}
return
0;
}
|
那么,如果容器里的元素是一个类呢?例如,有list<CPerson> ,其中CPerson类定义如下:
1
2
3
4
5
6
7
|
class
CPerson
{
public :
CPerson( void );
~CPerson( void );
public :
int
age; //
年龄
};
|
1
|
bool
operator==( const
CPerson &rhs) const ;
|
1
2
3
4
|
bool
CPerson::operator==( const
CPerson &rhs) const
{
return
(id == rhs.age);
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
list<CPerson>
lst;
//////////////////////////////////
//
向lst中添加元素,此处省略
//////////////////////////////////
CPerson
cp_to_find; //
要查找的对象
cp_to_find.age
= 50;
list<CPerson>::iterator
it = find(list.begin(), list.end(), cp_to_find); //
查找
if
(it != lst.end()) //
找到了
{
//
do something
}
else
// 没找到
{
//
do something
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
typedef
struct
finder_t
{
finder_t( int
n)
:
age(n)
{
}
bool
operator()(CPerson *p)
{
return
(age == p->age);
}
int
age;
}finder_t;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
list<CPerson*>
lst;
//////////////////////////////////
//
向lst中添加元素,此处省略
//////////////////////////////////
list<CPerson*>::iterator
it = find_if(lst.begin(), lst.end(), finder_t(50)); //
查找年龄为50的人
if
(it != lst.end()) //
找到了
{
cout
<< “Found person with age : ” << (*it)->age;
}
else
// 没找到
{
//
do something
}
if
(it != lst.end()) //
找到了
{
//
do something
}
else
// 没找到
{
//
do something
}
return
0;
}
|