c++list sortメソッド

4853 ワード

   1:  #include <list>
   2:  #include <string>
   3:  #include <functional>
   4:  #include <iostream>
   5:   
   6:  struct S {
   7:           std::string firstname;
   8:           std::string secondname;
   9:           int ID;
  10:           //       ,     sort         <,          <        
  11:          bool operator < (S & b) { 
  12:              return ID < b.ID;
  13:           }
  14:   
  15:  };
  16:  int main(int argc, char* argv[])
  17:  { 
  18:             std::list<S> mylist; 
  19:             std::list<S>::iterator iter; 
  20:             S a; 
  21:             a.firstname ="dfadf"; 
  22:             a.ID = 5; 
  23:             mylist.push_back (a);    
  24:            a.firstname ="  "; 
  25:             a.ID = 9; 
  26:             mylist.push_back (a);   
  27:             a.firstname ="xxx"; 
  28:             a.ID = 7;  
  29:            mylist.push_back (a);  
  30:            a.firstname ="gggg"; 
  31:            a.ID = 25; 
  32:             mylist.push_back (a); 
  33:              mylist.sort();
  34:            //      operator        ,    ,    sort    
  35:             for (iter = mylist.begin(); iter != mylist.end();++iter)  
  36:             {     
  37:                       std::cout <<static_cast<S>(*iter).ID << "\t"; 
  38:              } 
  39:             std::cout <<std::endl;      
  40:             return 0;
  41:   }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }