首页 > 后端开发 > C++ > 正文

c++中如何使用std::find和std::find_if算法_c++查找算法find与find_if用法

冰火之心
发布: 2025-10-23 10:56:02
原创
921人浏览过
std::find用于查找等于指定值的元素,std::find_if用于查找满足条件的第一个元素,两者均返回迭代器,需与end()比较判断是否找到。

c++中如何使用std::find和std::find_if算法_c++查找算法find与find_if用法

在C++中,std::findstd::find_if 是定义在 red"><algorithm> 头文件中的两个常用查找算法。它们用于在指定范围内搜索满足特定条件的元素,返回匹配元素的迭代器。如果未找到,则返回指向范围末尾的迭代器(即 end())。

std::find 的基本用法

std::find 用于在区间 [first, last) 中查找等于给定值的元素。

函数原型如下:

template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value);

参数说明:

立即学习C++免费学习笔记(深入)”;

  • first:起始迭代器
  • last:结束迭代器(不包含)
  • value:要查找的值

示例代码:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
auto it = std::find(vec.begin(), vec.end(), 30);

if (it != vec.end()) {
std::cout << "找到元素: " << *it << std::endl;
} else {
std::cout << "未找到元素" << std::endl;
}
return 0;
}

输出结果:

找到元素: 30

std::find_if 的基本用法

std::find_if 用于查找第一个满足指定条件的元素。条件由一个可调用对象(如函数指针、lambda 表达式或函数对象)定义。

函数原型:

法语写作助手
法语写作助手

法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。

法语写作助手 31
查看详情 法语写作助手
template<class InputIt, class UnaryPredicate>
InputIt find_if(InputIt first, InputIt last, UnaryPredicate p);

参数说明:

立即学习C++免费学习笔记(深入)”;

  • firstlast:搜索范围
  • p:一元谓词,返回 true 表示满足条件

示例:查找第一个偶数

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
std::vector<int> vec = {1, 3, 5, 8, 9, 10};
auto it = std::find_if(vec.begin(), vec.end(),
[](int x) { return x % 2 == 0; }); // lambda 判断是否为偶数

if (it != vec.end()) {
std::cout << "第一个偶数是: " << *it << std::endl;
} else {
std::cout << "未找到偶数" << std::endl;
}
return 0;
}

输出结果:

第一个偶数是: 8

结合自定义结构体使用 find_if

当容器中存储的是结构体或类对象时,可以使用 std::find_if 配合 lambda 或函数对象进行复杂条件查找。

#include <iostream>
#include <vector>
#include <algorithm>

struct Person {
std::string name;
int age;
};

int main() {
std::vector<Person> people = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 35}
};

auto it = std::find_if(people.begin(), people.end(),
[](const Person& p) { return p.name == "Bob"; });

if (it != people.end()) {
std::cout << "找到用户: " << it->name << ", 年龄: " << it->age << std::endl;
} else {
std::cout << "未找到用户" << std::endl;
}
return 0;
}

输出结果:

找到用户: Bob, 年龄: 30

基本上就这些。只要理解了迭代器范围和返回值的判断方式,再根据查找条件选择 find 或 find_if,就能高效完成常见查找任务。注意别忘了比较返回值是否等于 end() 来判断查找是否成功。

以上就是c++++中如何使用std::find和std::find_if算法_c++查找算法find与find_if用法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号