代码点读机 / C++ / find

find C++ · 常用功能

在关联容器或 string 中查找指定值/子串,返回位置或迭代器。

怎么用

容器.find(值) 或 字符串.find(子串)

小例子

#include <algorithm>
#include <vector>
std::vector<int> v = {1, 5, 3};
auto it = std::find(v.begin(), v.end(), 5);
std::string s = "abc";
std::cout << s.find("b");

运行结果

找到返回迭代器或位置;vector 示例输出 true,string 示例输出 1

提醒:容器与 string 的返回类型不同;vector 没有 .find(),用 std::find 并 include <algorithm>

官方文档:https://en.cppreference.com/w/cpp/string/basic_string/find

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← C++全部词条