std::find用于在vector中查找指定值,返回匹配元素的迭代器或end()。支持基本类型和重载==的自定义类型,复杂条件推荐使用std::find_if配合lambda。

在C++中,std::find 是标准库
std::find 基本用法
std::find 接收两个迭代器参数(表示查找范围)和一个目标值,返回指向第一个匹配元素的迭代器;若未找到,则返回第二个参数所指向的“末尾”迭代器(即 end())。
函数原型如下:
templateInputIt find(InputIt first, InputIt last, const T& value);
在 vector 中使用时,通常传入 begin() 和 end() 作为查找范围。
立即学习“C++免费学习笔记(深入)”;
在 vector 中查找基本类型元素
对于存储 int、double、string 等基本类型的 vector,使用 std::find 非常直观。
示例代码:
#include iostream>#include
#include
int main() {
std::vector
int target = 30;
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout } else {
std::cout }
return 0;
}
说明:通过比较返回的迭代器是否等于 vec.end() 来判断查找结果。使用 std::distance 可以计算出元素的下标位置。
查找自定义类型元素
如果 vector 存储的是自定义结构体或类对象,std::find 需要能够比较对象是否相等。这意味着必须重载 == 运算符,或者使用其他方式(如 std::find_if)进行条件匹配。
示例:
#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;
}
注意:这里重载了 operator==,使得 std::find 能正确比较两个 Person 对象。
使用 std::find_if 查找复杂条件
如果查找条件不是简单的值相等,比如查找年龄大于28的人,应使用 std::find_if 配合 lambda 表达式。
示例:
auto it = std::find_if(people.begin(), people.end(), [](const Person& p) {return p.age > 28;
});
if (it != people.end()) {
std::cout name }
这种方式更灵活,适用于任意判断逻辑。
基本上就这些。std::find 结合 vector 使用简单高效,适合查找已知值的元素。关键是要理解迭代器的语义以及如何判断查找结果。对于复杂匹配,推荐使用 std::find_if。










