C++ 标准库 - <algorithm>

C++ std::find 在 [first, last) 中查找第一个等于给定值的元素,返回指向它的迭代器;找不到则返回 last。

原型

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

参数

  • first, last:搜索区间。
  • value:目标值,用 operator== 比较。

返回值

指向首个匹配的迭代器,或 last。

示例

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

int main() {
    std::vector<int> v = {10, 20, 30};
    auto it = std::find(v.begin(), v.end(), 20);
    if (it != v.end()) {
        std::cout << *it << std::endl;
    }
    return 0;
}

输出:

20

注意事项

使用前必须与 end()(即传入的 last)比较,不可对失败结果解引用。按条件查找用 find_if。

下一页介绍find_if:按谓词查找。