C++ find函数详解_c++ find-优快云博客 来自这里(仅仅笔记自用)
C++中的find()函数有多种用法。它可以用于string类,用于查找字符或字符串。查找成功则返回第一个字符或者字串的位置,查找失败则返回string::npos即为-1。此外,find()也可以用于vector容器,用于查询指定元素是否存在。还有一个STL函数find(),它位于<algorithm>头文件下,返回一个迭代器,指向范围内搜索元素的第一次出现。
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v = {1, 2, 3, 4, 5};
auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end())
std::cout << "Element found: " << *it << '\n';
else
std::cout << "Element not found\n";
}
//上面的代码会在控制台输出“Element found: 3”。
<algorithm>下的find函数用于查找string类中的字符
它的用法与在其他容器中查找元素类似,只需将查找范围指定为字符串的起始和结尾即可。
下面这段代码演示了如何在一个字符串中查找指定字符:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "Hello, world!";
auto it = find(str.begin(), str.end(), 'w');
if (it != str.end())
cout << distance(str.begin(), it) << '\n'; // 输出7
else
cout << "Not found\n";
}
//上面的代码会在控制台输出“7”。
下面这段代码展示了如何使用search函数在一个string对象中查找子字符串"orld":
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello, world!";
std::cout << str.find("world") << '\n'; // 输出7
std::cout << str.find('w') << '\n'; // 输出7
std::cout << str.find("abc") << '\n'; // 输出18446744073709551615(即string::npos)
}
//上面的代码会在控制台输出“7\n7\n18446744073709551615”。
if(in.find("qiandao")!=in.npos||in.find("easy")!=in.npos){
continue;
}