std::find


本章描述C++泛型算法find的設計和使用。


我們先來看看C++官方網站上對find的描述

http://www.cplusplus.com/reference/algorithm/find/

(注:以下內容是我對C++官方網站上內容的理解,不准確的地方請見諒)

  • find函數的聲明:
template <class InputIterator, class T>
   InputIterator find (InputIterator first, InputIterator last, const T& val);
  • find函數的作用:

在[first,last)范圍內查找第一個與val相等的元素,並返回這個元素的迭代器(iterator),如果沒有找到,則返回last。

  • find函數的實現:

根據這個函數的實現,不難看出參數和返回值得類型,范圍和使用方法,這里不再贅述。

有一點需要注意,從函數的實現上我們可以看到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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM