C++的find函数 发表于 2017-08-05 | 分类于 C++ | 次 C++的find函数 头文件#include 函数实现12345678template <class InputIterator, class T>InputIterator find (InputIterator first, InputIterator last, const T&val){ while (first!=last){ if(*first==val) return first; ++first; } return last;} 例1123456789101112131415#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;} 例212345678910111213141516#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;} set,string自身有个find()函数 1234567891011121314151617181920212223242526272829303132#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; //find函数返回类型 size_type string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i"); string flag; string::size_type position; //find 函数 返回jk 在s 中的下标位置 position = s.find("jk"); if (position != s.npos) //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295, { cout << "position is : " << position << endl; } else { cout << "Not found the flag" + flag; }}