• <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>
  • 一個類數據類型的STL例子

    發表于:2007-07-01來源:作者:點擊數: 標簽:
    在STL編程中我們常見的數據類型是char int string等。若要用復雜數據類型(類類型),你必須重載必要的運算符。下例即演示了這一點: #include iostream #include list using namespace s td ; // 重載 運算符 class CMyClass { public: int x; int y; char

      在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

    原文轉自:http://www.kjueaiud.com

    老湿亚洲永久精品ww47香蕉图片_日韩欧美中文字幕北美法律_国产AV永久无码天堂影院_久久婷婷综合色丁香五月

  • <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>