本章描述C++泛型算法find的設計和使用。
我們先來看看C++官方網站上對find的描述
http://www.cplusplus.com/reference/algorithm/find/
(注:以下內容是我對C++官方網站上內容的理解,不准確的地方請見諒)
template <class InputIterator, class T> InputIterator find (InputIterator first, InputIterator last, const T& val);
在[first,last)范圍內查找第一個與val相等的元素,並返回這個元素的迭代器(iterator),如果沒有找到,則返回last。
根據這個函數的實現,不難看出參數和返回值得類型,范圍和使用方法,這裡不再贅述。
有一點需要注意,從函數的實現上我們可以看到find函數使用operator==來對元素是否相等進行判斷,所以,如果你需要比較的內容的元素類型是自定義類型,那麼你必須重載operator==。
1 template<class InputIterator, class T>
2 InputIterator find (InputIterator first, InputIterator last, const T& val)
3 {
4 while (first!=last)
5 {
6 if (*first==val) return first;
7 ++first;
8 }
9 return last;
10 }
理論上的東西基本就這些,以下是我寫的一個簡單的例子
1 #include <algorithm>
2
3 #include <iostream>
4 #include <string>
5 #include <vector>
6
7 using std::cout;
8 using std::endl;
9 using std::string;
10 using std::vector;
11
12 void print(vector<string> vec)
13 {
14 vector<string>::iterator iter;
15 for (iter = vec.begin(); iter != vec.end(); iter++)
16 {
17 cout << *iter << " ";
18 }
19 cout << endl;
20 }
21
22 int main(void)
23 {
24 vector<string> vec;
25 vec.push_back("a");
26 vec.push_back("b");
27 vec.push_back("c");
28 vec.push_back("d");
29 print(vec);
30
31 vector<string>::iterator iter;
32 iter = find(vec.begin(), vec.end(), "c");
33 if (iter != vec.end())
34 {
35 cout << "found it: " << *iter << endl;
36 }
37 return 0;
38 }
class TTT
{
public:
void FUN1(){cout<<"fun1"<<endl;}
void FUN2(){cout<<"fun2"<<endl;}
void FUN3(){cout<<"fun3"<<endl;}
protected:
private:
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<void (TTT::*)(void)> sg_MinUp;
sg_MinUp.push_back(&TTT::FUN1);
sg_MinUp.push_back(&TTT::FUN2);
sg_MinUp.push_back(&TTT::FUN3);
std::vector<void (TTT::*)(void)>::iterator ite = find(sg_MinUp.begin(),sg_MinUp.end(),&TTT::FUN2);
}
在VS2010上編譯通過。
if(find(v.begin(), v.end(), val) != v.end()){ //找到}else{ //沒找到}val為要找的元素