C++中find_if查找vector中的特定struct以及值域查询

由于struct不是C++中的内置类型所以不能用std::find直接查找,而且find函数不能满足值域的查询。这个时候需要使用find_if来进行查询。

find_if函数

find_if是一个模板函数,函数原型及函数定义:

1
2
3
4
5
template <class InputIterator, class Predicate>
InputIterator find_if(InputIterator first, InputIterator end, Predicate pred) {
while (first != last && !pred(*first)) ++first;
return first;
}

函数参数

  • first : 起始迭代器
  • end : 结束迭代器
  • pred : 用于比较数值的函数或者函数对象(仿函数)。遍历条件即为pred()为真.

函数返回值

若有满足pred条件的元素,返回该元素的迭代器,否则返回end.

函数说明

该函数最重要的环节是pred,它的核心环节是重载()运算符,因为每个容器迭代器的*运算符得到的结果都是该容器的value_type的值,所以改重载函数的参数类型是value_type的引用类型

find_if函数应用

在struct的vector中查找特定的对象.特别注意的是:仿函数的参数类型是值的const引用,但是finder的构造参数是实际要比较的值的类型,在使用过程中,向构造函数中传的值是要比较的值。

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
struct book{
int m_iID;
string m_strName;
book(int t_id, string t_name):m_iID(t_id), m_strName(t_name) {}
};
struct book_finder{
int m_iID;
book_finder(int t_id):m_iID(t_id) {}
bool operator() (const book& t) {return t.m_iID == m_iID;}
};
int main() {
vector<book> bookVc;
book book1(0, "书0");
book book2(1, "书1");
book book3(2, "书2");
book book4(3, "书3");
bookVc.push_back(book1);
bookVc.push_back(book2);
bookVc.push_back(book3);
bookVc.push_back(book4);
book target(1, "书");
if (std::find_if(bookVc.begin(), bookVc.end(), book_finder(target.m_iID)) != bookVc.end()) {
cout << "存在1" << std::endl;
} else {
cout << "不存在1" << std::endl;
}
target.m_iID = 10;
if (std::find_if(bookVc.begin(), bookVc.end(), book_finder(target.m_iID)) != bookVc.end()) {
cout << "存在10" << std::endl;
} else {
cout << "不存在10" << std::endl;
}
}

Comment and share

  • page 1 of 1

魏传柳(2824759538@qq.com)

author.bio


Tencent


ShenZhen,China