std::find用于在容器中查找指定值,需包含头文件,传入迭代器范围和目标值,返回匹配元素的迭代器或end()。

在C++中,std::find 是一个非常常用的算法函数,用于在指定范围内查找某个值。它定义在
std::find 基本用法
std::find 接收两个迭代器参数(表示查找范围)和一个目标值,返回第一个匹配元素的迭代器。如果未找到,则返回第二个参数(即末尾迭代器 end())。
函数原型如下:
template
InputIt std::find(InputIt first, InputIt last, const T& value);
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include iostream>#include
#include
int main() {
std::vector
auto it = std::find(vec.begin(), vec.end(), 30);
if (it != vec.end()) {
std::cout } else {
std::cout }
return 0;
}
在自定义类型中使用 std::find
如果你的容器存储的是自定义类型(如类或结构体),需要重载 == 运算符,否则 std::find 无法比较对象是否相等。
示例:
#include#include
#include
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
int main() {
std::vector
Person target = {"Bob", 30};
auto it = std::find(people.begin(), people.end(), target);
if (it != people.end()) {
std::cout name age } else {
std::cout }
return 0;
}
结合 lambda 使用 find_if
如果查找条件更复杂(比如只根据名字查找,不关心年龄),可以使用 std::find_if 配合 lambda 表达式。
示例:查找名字为 "Alice" 的人
auto it = std::find_if(people.begin(), people.end(),[](const Person& p) { return p.name == "Alice"; });
if (it != people.end()) {
std::cout name }
基本上就这些。只要记住包含头文件











