码迷,mamicode.com
首页 > 其他好文 > 详细

std find,std find if对类进行查找

时间:2019-02-27 12:56:47      阅读:615      评论:0      收藏:0      [点我收藏+]

标签:lse   数据   com   turn   相等   需要   定义   span   ant   

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; // 年龄
};
那么如何用find()函数进行查找呢?这时,我们需要提供一个判断两个CPerson对象“相等”的定义,find()函数才能从一个list中找到与指定的CPerson“相等”的元素。
文章来源:http://www.codelast.com/
这个“相等”的定义,是通过重载“==”操作符实现的,我们在CPerson类中添加一个方法,定义为:
1
bool operator==(const CPerson &rhs) const;
实现为:
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net

std find,std find if对类进行查找

标签:lse   数据   com   turn   相等   需要   定义   span   ant   

原文地址:https://www.cnblogs.com/sjwudhwhhw/p/10442907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!