C++中的結構體vector排序


在包含了頭文件#include <algorithm>之后,就可以直接利用sort函數對一個vector進行排序了:

 1 // sort algorithm example  
 2 #include <iostream>     // std::cout  
 3 #include <algorithm>    // std::sort  
 4 #include <vector>       // std::vector  
 5   
 6 bool myfunction (int i,int j) { return (i<j); }  
 7   
 8 struct myclass {  
 9   bool operator() (int i,int j) { return (i<j);}  
10 } myobject;  
11   
12 int main () {  
13   int myints[] = {32,71,12,45,26,80,53,33};  
14   std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33  
15   
16   // using default comparison (operator <):  
17   std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33  
18   
19   // using function as comp  
20   std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)  
21   
22   // using object as comp  
23   std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)  
24   
25   // print out content:  
26   std::cout << "myvector contains:";  
27   for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)  
28     std::cout << ' ' << *it;  
29   std::cout << '\n';  
30   
31   return 0;  
32 }  

但是當vector中的變量是結構體,並且需要按照結構體的某一個元素進行排序時,則需要進行一定的修改:

 

 1 #include "privateHeader.h"
 2 #include <string>
 3 #include <vector>
 4 #include <iostream>
 5 #include <algorithm>
 6 using std::string;
 7 using std::vector;
 8 using std::cout;
 9 using std::endl;
10 using namespace std;
11 
12 typedef struct
13 {
14     float score;
15     string file_name;
16     string all_file_name;
17 
18 }TFileProp;
19 
20 bool GreaterSort(TFileProp a, TFileProp b)
21 { 
22     return (a.score > b.score);
23 }
24 bool LessSort(TFileProp a, TFileProp b)
25 { 
26     return (a.score < b.score);
27 }
28 vector<TFileProp> VecFileProp;
29 
30 VecFileProp.push_back(tFileProp);    //對vector進行push操作
31 
32 std::sort(VecFileProp.begin(), VecFileProp.end(), GreaterSort);    //進行降序排序
33 std::sort(VecFileProp.begin(), VecFileProp.end(), LessSort);    //進行升序排序

 

還有一點,利用Iang傳遞參一個數據時,由於命令行接收的參數是以char** argv存儲的,因此需要先進行強制類型轉換,經過一個string作為中間的轉換變量,最終轉成int型,另外,我之前認為由於是char型的原因,應該主能傳遞0-255的參數,但是仔細想一下是不對的,因為無論是多大的數,都是以一個字符串傳遞進去的,然后string類型再進行強轉的時候就轉陳了int型,因此並不存在256的大小限制。

 1 int main(int argc, char** argv)
 2 {
 3     // 統計時間
 4     //timeStatistics();
 5 
 6     // 所有結果放到一個文件夾顯示
 7     
 8     int num_save;
 9     if (argc == 2)
10     {
11         std::string thres = argv[1];
12         num_save = atof(thres.c_str());
13         //std::cout << "(int)argv[1] is " << argv[1];
14         //std::cout << "num_save is " << num_save;
15     }
16     else
17     {
18         num_save = 100;
19     }
20     showAllResult(num_save);
21     
22     
23     return 1;
24 }

 

 

 

參考:http://blog.csdn.net/zhouxun623/article/details/49887555


免責聲明!

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



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