码迷,mamicode.com
首页 > 编程语言 > 详细

c++ list sort

时间:2014-10-25 14:27:37      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   strong   sp   

  1.    bool operator < (S & b) {
       return ID < b.ID;
      }

struct S {
         std::string firstname;
         std::string secondname;
         int ID;
      bool operator < (S & b) {
       return ID < b.ID;
      }
 // 重新定义小于,因为默认的sort函数调用的操作符是<,所以我们只需要重载 < 就好了
};

int main(int argc, char* argv[])
{
 
 std::list<S> mylist;
 
 std::list<S>::iterator iter;
 
 S a;
 
 a.firstname ="dfadf";
 
 a.ID = 5;
 
 mylist.push_back (a);
 
 
 
 a.firstname ="得到";
 
 a.ID = 9;
 
 mylist.push_back (a);
 
 
 
 a.firstname ="xxx";
 
 a.ID = 7;
 
 mylist.push_back (a);
 
 
 
 a.firstname ="gggg";
 
 a.ID = 25;
 
 mylist.push_back (a);
 
 
 
 mylist.sort();

2.


#include "stdafx.h"
#include <iostream> 
#include <list>
using namespace std;
 
class A{
public:
    A(int m):a(m){}
    bool operator <(const A& other)
    {
    <span style="font-size: 18px;">    return a < other.a;</span>
    }
    friend std::ostream& operator <<(std::ostream& out, const A& obj){
        out<< obj.a<<endl;
        return out;
    }
private:
    int a;
};
 
 
int _tmain(int argc, _TCHAR* argv[])
{  
   list<A> S;
   typedef list<A>::iterator it;
   S.push_back(A(3));
   S.push_back(A(2));
   S.push_back(A(5));
   S.sort();
    it it1 = S.begin();
    it it2 = S.end();
    while(it1 != it2)
    {
        cout<<*it1<<endl;
        it1++;
    }
    return 0;
}

3.

33 // list_sort.cpp
34 // compile with: /EHsc
35 #include <list>
36 #include <iostream>
37  
38 int main( )
39 {
40    using namespace std;
41    list <int> c1;
42    list <int>::iterator c1_Iter;
43     
44    c1.push_back( 20 );
45    c1.push_back( 10 );
46    c1.push_back( 30 );
47  
48    cout << "Before sorting: c1 =";
49    for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
50       cout << " " << *c1_Iter;
51    cout << endl;
52  
53    c1.sort( );
54    cout << "After sorting c1 =";
55    for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
56       cout << " " << *c1_Iter;
57    cout << endl;
58  
59    c1.sort( greater<int>( ) );
60    cout << "After sorting with ‘greater than‘ operation, c1 =";
61    for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
62       cout << " " << *c1_Iter;
63    cout << endl;
64 }

 

c++ list sort

标签:style   blog   color   io   os   ar   for   strong   sp   

原文地址:http://www.cnblogs.com/yelongsan/p/4050026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!