您可以在这里快速查找:


 
您的位置: 编程学习 > C++/VC > 200512
文章分类

Java技术
2005: 03 04 05 06 07 08
09 10 11 12
2006: 01 02

Asp.net
2005: 07 08 09 10 11 12
2006: 01 02

VB编程
2006: 02

Asp编程
2005: 11 12
2006: 01 02

C++/VC
2005: 10 11 12
2006: 01 02

Delphi
2005: 12
2006: 01 02

其它

 本文章适合所有读者

一个类数据类型的STL例子

sun4216

  在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