轉:http://www.cnblogs.com/kaituorensheng/p/4072901.html (C++中find函數)
http://blog.csdn.net/huangyimin/article/details/6133650 (用於vector的find函數及STL的理解筆記)
find函數主要實現的是在容器內查找指定的元素,並且這個元素必須是基本數據類型的。查找成功返回一個指向指定元素的迭代器,查找失敗返回end迭代器。
注意:
- find() 不屬於 vector 的成員,而存在於算法中,應加上頭文件 #include <algorithm>;
- string::find 這類型的函數,返回值類型都是 string::size_type (或者寫為 size_t 型), 而 string::size_type 其實是一種 unsigned int 類型。find 的結果記錄匹配的位置,或者返回一個名為 string::npos 的特殊值,說明查找沒有匹配。string 類將 npos 定義為保證大於任何有效下標的值。string::npos 的值是無符號型類型的,其值是(unsigned int)(-1),也就是4294967295。
頭文件
#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;
}

