#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<Person> people = {
{"Alice", 25},
{"John", 35},
{"Bob", 28},
{"John", 22}
};
auto it = std::find_if(people.begin(), people.end(), [](const Person& p) {
return p.name == "John" && p.age > 30;
});
if (it != people.end()) {
std::cout << "找到符合条件的Person对象,名字: " << it->name << ",年龄: " << it->age << std::endl;
} else {
std::cout << "未找到符合条件的Person对象" << std::endl;
}
return 0;
}
实现思路
- 定义结构体:首先定义了
Person
结构体,包含 name
和 age
两个成员变量,分别表示名字和年龄。
- 创建容器:创建一个
std::vector<Person>
容器,并初始化一些 Person
对象。
- 使用
find_if
算法:find_if
是 C++ STL 中的算法,用于在指定范围内查找满足特定条件的第一个元素。这里我们传入容器的起始迭代器 people.begin()
和结束迭代器 people.end()
,以及一个 lambda 表达式作为判断条件。
- lambda 表达式:lambda 表达式
[](const Person& p) { return p.name == "John" && p.age > 30; }
用于判断 Person
对象是否满足名字为 "John" 且年龄大于 30 的条件。
- 判断结果:如果找到了符合条件的对象,
find_if
返回指向该对象的迭代器,否则返回 people.end()
。通过判断返回的迭代器是否等于 people.end()
,我们可以得知是否找到了符合条件的对象,并进行相应输出。