深入理解C++ std::find

发布时间:2026/10/26 9:08:29
深入理解C++ std::find std::find详解1. 它是什么std::find定义在algorithm头文件中用于在区间[first, last)中线性查找第一个等于给定值的元素。2. 函数签名C17 及之前cpptemplate class InputIt, class T InputIt find(InputIt first, InputIt last, const T value);C20 起增加了constexprcpptemplate class InputIt, class T constexpr InputIt find(InputIt first, InputIt last, const T value);C20 还提供了 ranges 版本可以直接传容器不必写begin()/end()cpptemplate ranges::input_range R, class T constexpr ranges::borrowed_iterator_tR find(R r, const T value);3. 参数与返回值参数含义first起始迭代器包含last结束迭代器不包含value要查找的值返回值找到返回指向第一个匹配元素的迭代器没找到返回last。复杂度最多std::distance(first, last)次比较即 O(n)。要求表达式*it value必须合法也就是元素类型和value之间要有可用的operator。4. 典型用法cppauto it std::find(v.begin(), v.end(), target); if (it ! v.end()) { // 找到了*it 就是匹配元素 // std::distance(v.begin(), it) 是下标 } else { // 没找到 }关键点是一定要拿返回值和end()比较不要直接解引用也不要用if (it)判断迭代器没有这种真假语义。#include algorithm #include iostream #include iterator #include string #include vector struct Person { std::string name; int age; bool operator(const Person other) const { return name other.name age other.age; } }; int main() { // ---------- 1. vectorint 基础查找 ---------- std::vectorint v{3, 1, 4, 1, 5, 9, 2, 6}; auto it std::find(v.begin(), v.end(), 5); if (it ! v.end()) { std::cout [1] found 5 at index std::distance(v.begin(), it) \n; } // ---------- 2. 找不到的情况 ---------- auto it2 std::find(v.begin(), v.end(), 42); if (it2 v.end()) { std::cout [2] 42 not found\n; } // ---------- 3. 返回的是第一个匹配 ---------- std::vectorint dup{1, 2, 2, 3, 2}; auto it3 std::find(dup.begin(), dup.end(), 2); std::cout [3] first 2 at index std::distance(dup.begin(), it3) \n; // ---------- 4. 在 string 里找字符 ---------- std::string s hello world; auto it4 std::find(s.begin(), s.end(), w); if (it4 ! s.end()) { std::cout [4] found w at position (it4 - s.begin()) \n; } // ---------- 5. 自定义类型需要 operator ---------- std::vectorPerson people{ {Alice, 30}, {Bob, 25}, {Carol, 35} }; auto it5 std::find(people.begin(), people.end(), Person{Bob, 25}); if (it5 ! people.end()) { std::cout [5] found it5-name , age it5-age \n; } // ---------- 6. C20 ranges 版本 ---------- #if __cplusplus 202002L auto it6 std::ranges::find(v, 9); if (it6 ! v.end()) { std::cout [6] ranges::find found 9 at index std::distance(v.begin(), it6) \n; } #endif return 0; }

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询