c++find函数用法
头文件
#include <algorithm>
函数实现

template<class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val) { while (first!=last) { if (*first==val) return first; ++first; } return last; }

例1(vector)

#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<string> m; m.push_back("hello"); m.push_back("hello2"); m.push_back("hello3"); if (find(m.begin(), m.end(), "hello") == m.end()) cout << "no" << endl; else cout << "yes" << endl; }

例2(set)

#include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; int main() { set<string> m; m.insert("hello"); m.insert("hello2"); m.insert("hello3"); if (find(m.begin(), m.end(), "hello") == m.end()) cout << "no" << endl; else cout << "yes" << endl; }

注1:set自身有个find函数,举例如下:

#include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; int main() { set<string> m; m.insert("hello"); m.insert("hello2"); m.insert("hello3"); if (find(m.begin(), m.end(), "hello") == m.end()) cout << "no" << endl; else cout << "yes" << endl; }

注2:string自身有个find函数,举例如下:

#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string s = "helllo"; if (s.find("e") == string::npos) //yes cout << "no" << endl; else cout << "yes" << endl; if (s.find("z") == string::npos) //no cout << "no" << endl; else cout << "yes" << endl; }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: sa_flags
- 下一篇: C/C++ 连接两个字符串