std::find用于查找等于指定值的元素,std::find_if用于查找满足条件的第一个元素,两者均返回迭代器,需与end()比较判断是否找到。

在C++中,std::find 和 std::find_if 是定义在 red"><algorithm> 头文件中的两个常用查找算法。它们用于在指定范围内搜索满足特定条件的元素,返回匹配元素的迭代器。如果未找到,则返回指向范围末尾的迭代器(即 end())。
std::find 的基本用法
std::find 用于在区间 [first, last) 中查找等于给定值的元素。
函数原型如下:
template<class InputIt, class T>InputIt find(InputIt first, InputIt last, const T& value);
参数说明:
立即学习“C++免费学习笔记(深入)”;
- first:起始迭代器
- last:结束迭代器(不包含)
- value:要查找的值
示例代码:
#include <iostream>#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
auto it = std::find(vec.begin(), vec.end(), 30);
if (it != vec.end()) {
std::cout << "找到元素: " << *it << std::endl;
} else {
std::cout << "未找到元素" << std::endl;
}
return 0;
}
输出结果:
找到元素: 30std::find_if 的基本用法
std::find_if 用于查找第一个满足指定条件的元素。条件由一个可调用对象(如函数指针、lambda 表达式或函数对象)定义。
函数原型:
InputIt find_if(InputIt first, InputIt last, UnaryPredicate p);
参数说明:
立即学习“C++免费学习笔记(深入)”;
- first、last:搜索范围
- p:一元谓词,返回 true 表示满足条件
示例:查找第一个偶数
#include <iostream>#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 3, 5, 8, 9, 10};
auto it = std::find_if(vec.begin(), vec.end(),
[](int x) { return x % 2 == 0; }); // lambda 判断是否为偶数
if (it != vec.end()) {
std::cout << "第一个偶数是: " << *it << std::endl;
} else {
std::cout << "未找到偶数" << std::endl;
}
return 0;
}
输出结果:
第一个偶数是: 8结合自定义结构体使用 find_if
当容器中存储的是结构体或类对象时,可以使用 std::find_if 配合 lambda 或函数对象进行复杂条件查找。
#include <iostream>#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<Person> people = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 35}
};
auto it = std::find_if(people.begin(), people.end(),
[](const Person& p) { return p.name == "Bob"; });
if (it != people.end()) {
std::cout << "找到用户: " << it->name << ", 年龄: " << it->age << std::endl;
} else {
std::cout << "未找到用户" << std::endl;
}
return 0;
}
输出结果:
找到用户: Bob, 年龄: 30基本上就这些。只要理解了迭代器范围和返回值的判断方式,再根据查找条件选择 find 或 find_if,就能高效完成常见查找任务。注意别忘了比较返回值是否等于 end() 来判断查找是否成功。










