std::find用于在指定范围内查找目标值,返回首个匹配元素的迭代器或last。支持vector、数组及自定义类型(需重载==),常配合distance计算索引,复杂条件应使用find_if。

std::find 是 C++ STL 中一个常用的算法,用于在指定范围内查找某个值的第一次出现位置。它定义在头文件
基本语法
std::find 的函数原型如下:template参数说明:InputIt find(InputIt first, InputIt last, const T& value);
- first:起始迭代器,表示查找范围的开始(包含)。
- last:结束迭代器,表示查找范围的末尾(不包含)。
- value:要查找的目标值。
如果找到目标值,返回指向第一个匹配元素的迭代器;否则返回 last 迭代器。
在 vector 中使用 std::find
常见用法是在 std::vector 中查找某个元素:
#include#include #include int main() { std::vector
vec = {10, 20, 30, 40, 50}; auto it = std::find(vec.begin(), vec.end(), 30); if (it != vec.end()) { std::cout << "找到了,值为:" << *it << std::endl; std::cout << "索引位置:" << std::distance(vec.begin(), it) << std::endl; } else { std::cout << "未找到该值" << std::endl; } return 0;}
在数组中使用 std::find
也可以用于普通数组:
立即学习“C++免费学习笔记(深入)”;
#include#include int main() { int arr[] = {5, 3, 8, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]);
auto it = std::find(arr, arr + n, 8); if (it != arr + n) { std::cout << "找到了,值为:" << *it << std::endl; std::cout << "索引:" << it - arr << std::endl; } else { std::cout << "未找到" << std::endl; } return 0;}
查找自定义类型或复杂对象
如果要在自定义结构体或类中查找,需确保类型支持相等比较(== 操作符),或者改用 std::find_if 配合谓词函数。
#include#include #include struct Person { int id; std::string name; bool operator==(const Person& other) const { return id == other.id; } };
int main() { std::vector
people = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}}; Person target{2, ""}; auto it = std::find(people.begin(), people.end(), target); if (it != people.end()) { std::cout << "找到用户:" << it->name << std::endl; } else { std::cout << "未找到" << std::endl; } return 0;}
基本上就这些。只要记住传入正确的迭代器范围,检查返回值是否等于 end(),就能安全使用 std::find。对于更复杂的条件查找,建议使用 std::find_if。











