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 = ; mylist.push_back (a); a.firstname ="得到"; a.ID = ; mylist.push_back (a); a.firstname ="xxx"; a.ID = ; mylist.push_back (a); a.firstname ="gggg"; a.ID = ; 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());
S.push_back(A());
S.push_back(A());
S.sort();
it it1 = S.begin();
it it2 = S.end();
while(it1 != it2)
{
cout<<*it1<<endl;
it1++;
}
return ;
}
3.
// list_sort.cpp
// compile with: /EHsc
#include <list>
#include <iostream> int main( )
{
using namespace std;
list <int> c1;
list <int>::iterator c1_Iter; c1.push_back( );
c1.push_back( );
c1.push_back( ); cout << "Before sorting: c1 =";
for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
cout << " " << *c1_Iter;
cout << endl; c1.sort( );
cout << "After sorting c1 =";
for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
cout << " " << *c1_Iter;
cout << endl; c1.sort( greater<int>( ) );
cout << "After sorting with 'greater than' operation, c1 =";
for ( c1_Iter = c1.begin( ); c1_Iter != c1.end( ); c1_Iter++ )
cout << " " << *c1_Iter;
cout << endl;
}