std::find用于在迭代器范围内查找目标值,返回首个匹配元素的迭代器或end()。支持数组、vector、string等容器,自定义类型需重载==操作符。

std::find 是 C++ 标准库中定义在 头文件里的一个通用查找算法,用于在指定范围内查找某个值的第一次出现位置。它不局限于某一种容器,可以用于数组、vector、list、deque 等任何支持迭代器的序列容器。
std::find 基本用法
函数原型如下:
templateInputIt find(InputIt first, InputIt last, const T& value);
参数说明:
- first:起始迭代器,表示查找范围的开始
- last:结束迭代器,表示查找范围的末尾(不包含)
- value:要查找的值
返回值:如果找到目标元素,返回指向第一个匹配元素的迭代器;否则返回 last 迭代器。
立即学习“C++免费学习笔记(深入)”;
在 vector 中使用 std::find 查找元素
以下是一个在 std::vector 中查找整数的例子:
#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;
}
输出结果:
找到元素: 30,位置索引: 2在 string 容器中查找字符
std::string 也支持迭代器,可以用 std::find 查找字符:
#include#include
#include
int main() {
std::string str = "Hello, world!";
char target = 'w';
auto it = std::find(str.begin(), str.end(), target);
if (it != str.end()) {
std::cout } else {
std::cout }
return 0;
}
输出:
找到字符 'w',位置: 7查找自定义类型对象
若要在存储自定义类型的容器中使用 std::find,需确保类型重载了 == 操作符。
#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;
}
输出:
找到人物: Bob, 年龄: 30基本上就这些。只要容器提供迭代器,std::find 就能用。注意比较操作必须有意义,基础类型自动支持,自定义类型记得重载 ==。查找失败时返回 end(),记得判断。










