
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; }