在STL编程中我们常见的数据类型是char int string等。若要用复杂数据类型(类类型),你必须重载必要的运算符。下例即演示了这一点:
#include <iostream>
#include <list>
using namespace std;
// 重载 < 运算符
class CMyClass
{
public:
int x;
int y;
char z;
CMyClass()
{
x = 0;
y = 0;
z = ' ';
}
~CMyClass(){};
void print(const CMyClass &CMyClass)
{
cout << CMyClass.x << ' ' << CMyClass.y << ' ' << CMyClass.z << endl;
}
int operator<(const CMyClass &rhs) const
{
if( this->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1;
if( this->x == rhs.x && this->y < rhs.y) return 1;
if( this->x < rhs.x ) return 1;
return 0;
}
};
// 必须用LIST模版类的内建SORT函数排序
list<CMyClass> sortIt( list<CMyClass>& myList)
{
myList.sort();
return myList;
}
main()
{
list<CMyClass> myList, sortedList;
CMyClass MyClass ;
MyClass.x=3;
MyClass.y=2;
MyClass.z='A';
myList.push_back(MyClass);
MyClass.x=2;
myList.push_back(MyClass);
MyClass.z='B';
myList.push_back(MyClass);
MyClass.x=1;
MyClass.y=5;
MyClass.z='C';
myList.push_back(MyClass);
list<CMyClass>::iterator i;
for(i=myList.begin(); i != myList.end(); ++i)
{
cout<< " ";
MyClass.print(*i);
}
cout << endl;
sortedList = sortIt( myList );
cout << "Sorted: " << endl;
for(i=sortedList.begin(); i != sortedList.end(); ++i)
{
cout<< " ";
MyClass.print(*i);
}
cout << endl;
return 0;
}
输出:
3 2 A
2 2 A
2 2 B
1 5 C
Sorted:
1 5 C
2 2 A
2 2 B
3 2 A