使用標准模板find函數來對結構體容器進行查找


最近在寫一個項目,項目中需要獲得類下面的所有對象,所以我采用了map容器,以string為關鍵字,list容器為內容來進行查找,而list中是一些struct結構體。由於在插入操作的時候需要判斷該對象是否存在,所以需要對list的對象進行查找。我不太喜歡用ForEach的方法,所以采用了標准模板find函數,而find函數要求對象必須能夠支持==,所以事先必須重載,這個很容易忘記。

貼代碼:

 1 #include "iostream"
 2 #include "vector"
 3 #include "algorithm"
 4 using namespace std;
 5  
 6 struct st {
 7     int a;
 8     int b;
 9     st(int _a = 0, int _b = 0) : a(_a), b(_b) {}
10 };
11  
12 bool operator == (const st& left, const st& rigt) 
13 {
14     return left.a == rigt.a && left.b == rigt.b;
15 }
16  
17 int main() 
18 {
19     vector<st> vst;
20  
21     vst.push_back(st(0, 1));
22     vst.push_back(st(0, 2));
23     vst.push_back(st(1, 2));
24     vst.push_back(st(5, 1));
25     vst.push_back(st(5, 5));
26  
27     st t = st(5, 1);
28  
29     vector<st>::iterator ifind = find(vst.begin(), vst.end(), t);
30     if (ifind != vst.end())
31     {
32         cout<<"finded"<<endl;
33     }
34  
35     return 0;
36 }

 

轉載請注明出處:http://www.cnblogs.com/fnlingnzb-learner/p/5889026.html


免責聲明!

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



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