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

std::find 是 C++ STL 中一个常用的算法,用于在指定范围内查找某个值的第一次出现位置。它定义在头文件 <algorithm> 中,适用于任何支持迭代器的容器。
template<class InputIt, class T> InputIt find(InputIt first, InputIt last, const T& value);
如果找到目标值,返回指向第一个匹配元素的迭代器;否则返回 last 迭代器。
常见用法是在 std::vector 中查找某个元素:
#include <iostream>
#include <vector>
#include <algorithm>
<p>int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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;}
也可以用于普通数组:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <algorithm>
<p>int main() {
int arr[] = {5, 3, 8, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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 <iostream>
#include <vector>
#include <algorithm>
<p>struct Person {
int id;
std::string name;
bool operator==(const Person& other) const {
return id == other.id;
}
};</p><p>int main() {
std::vector<Person> people = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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。
以上就是c++++中std::find算法怎么用_C++ STL std::find算法使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号