std::find用于查找等于指定值的元素,返回匹配项迭代器或末尾;std::find_if通过谓词查找首个满足条件的元素,适用所有提供迭代器的容器,支持自定义类型与lambda表达式,时间复杂度O(n),适合无序数据搜索。

std::find 和 std::find_if 是 C++ 标准库中定义在 <algorithm> 头文件中的两个常用查找算法,用于在指定范围内搜索满足条件的元素。它们不会修改容器内容,返回的是迭代器,表示第一个匹配位置或末尾迭代器(未找到时)。
std::find 用于在区间 [first, last) 中查找等于给定值的第一个元素。
template <class InputIt, class T><br> InputIt find(InputIt first, InputIt last, const T& value);
参数说明:
- first:起始迭代器
- last:结束迭代器(不包含)
- value:要查找的值
返回值: 找到则返回指向第一个匹配元素的迭代器;否则返回 last。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream><br>#include <vector><br>#include <algorithm><br><br>int main() {<br>    std::vector<int> vec = {10, 20, 30, 40, 50};<br><br>    auto it = std::find(vec.begin(), vec.end(), 30);<br><br>    if (it != vec.end()) {<br>        std::cout << "找到元素: " << *it << std::endl;<br>    } else {<br>        std::cout << "未找到元素" << std::endl;<br>    }<br><br>    return 0;<br>}输出:找到元素: 30
std::find_if 用于查找第一个满足指定条件的元素,条件通过可调用对象(如 lambda、函数指针或函数对象)传入。
template <class InputIt, class UnaryPredicate><br> InputIt find_if(InputIt first, InputIt last, UnaryPredicate p);
参数说明:
- first, last:搜索范围
- p:一元谓词,接受一个参数并返回布尔值
返回值: 第一个使谓词返回 true 的元素迭代器,否则返回 last。
示例代码:使用 lambda 查找第一个偶数
#include <iostream><br>#include <vector><br>#include <algorithm><br><br>int main() {<br>    std::vector<int> vec = {1, 3, 5, 8, 9, 10};<br><br>    auto it = std::find_if(vec.begin(), vec.end(),<br>        [](int x) { return x % 2 == 0; });<br><br>    if (it != vec.end()) {<br>        std::cout << "第一个偶数是: " << *it << std::endl;<br>    } else {<br>        std::cout << "未找到偶数" << std::endl;<br>    }<br><br>    return 0;<br>}输出:第一个偶数是: 8
支持的容器类型:
- 所有提供迭代器的 STL 容器(如 vector、list、array、deque 等)
- 原生数组也可使用(配合指针)
自定义类型查找:
若要在自定义结构体中查找,需确保重载了 == 操作符(对 find),或正确编写判断逻辑(对 find_if)。
示例:在结构体中查找特定姓名
#include <iostream><br>#include <vector><br>#include <algorithm><br>#include <string><br><br>struct Person {<br>    std::string name;<br>    int age;<br>};<br><br>int main() {<br>    std::vector<Person> people = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 35}};<br><br>    auto it = std::find_if(people.begin(), people.end(),<br>        [](const Person& p) { return p.name == "Bob"; });<br><br>    if (it != people.end()) {<br>        std::cout << "找到: " << it->name << ", 年龄: " << it->age << std::endl;<br>    }<br><br>    return 0;<br>}性能提示:
- 两者时间复杂度为 O(n),适用于无序数据
- 对有序数据,考虑使用 binary_search、lower_bound 等更高效算法
基本上就这些。掌握 std::find 和 std::find_if 能显著提升代码可读性和安全性,避免手写循环出错。
以上就是c++++怎么使用std::find和std::find_if算法_c++查找算法find用法详解的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号