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

c++中std::find算法怎么用_C++ STL std::find算法使用方法

冰火之心
发布: 2025-09-28 18:46:12
原创
520人浏览过
std::find用于在指定范围内查找目标值,返回首个匹配元素的迭代器或last。支持vector、数组及自定义类型(需重载==),常配合distance计算索引,复杂条件应使用find_if。

c++中std::find算法怎么用_c++ stl std::find算法使用方法

std::find 是 C++ STL 中一个常用的算法,用于在指定范围内查找某个值的第一次出现位置。它定义在头文件 <algorithm> 中,适用于任何支持迭代器的容器。

基本语法

std::find 的函数原型如下:
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value);
登录后复制
参数说明:
  • first:起始迭代器,表示查找范围的开始(包含)。
  • last:结束迭代器,表示查找范围的末尾(不包含)。
  • value:要查找的目标值。
返回值:

如果找到目标值,返回指向第一个匹配元素的迭代器;否则返回 last 迭代器。

在 vector 中使用 std::find

常见用法是在 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;
登录后复制

}

在数组中使用 std::find

也可以用于普通数组:

豆绘AI
豆绘AI

豆绘AI是国内领先的AI绘图与设计平台,支持照片、设计、绘画的一键生成。

豆绘AI 485
查看详情 豆绘AI

立即学习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++在哪学?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号