一個排序用的C++函數模板

來源:互聯網
上載者:User

前段時間編寫MFC程式時,需要對一個字串集合CStringArray進行排序。標準模板庫STL提供的函數模板sort雖然功能強大,但有兩個不便:

1、 sort使用列舉程式(iterator)機制處理C++數組(即指標)和諸如vector這樣的STL對象,但MFC集合類CArray、CStringArray沒有提供列舉程式。雖然可以通過集合類的成員函數GetData把集合轉換成指標,然後調用sort進行處理,但這樣做破壞了對象的封裝性。

2、如果使用降序排序,還需要另外編一個比較函數。

為此我自己編寫了一個排序用的函數模板,一方面滿足自己的需求,另一方面也順便鞏固一下C++基礎。該函數模板雖然功能簡單一些,但支援C++數組和MFC集合類,支援升序和降序,對於一般應用來說足夠了。

函數代碼如下:
// 該函數模板使用冒泡法對集合元素進行排序,參數說明:
//   collection    集合對象,集合對象必須提供 [] 操作。
//   element     集合元素,該參數的作用僅僅是確定集合元素類型,
//           參數的值沒有用,建議取集合的第一個元素。集合
//           元素必須提供複製、賦值和比較操作。
//   count      集合元素的數目
//   ascend      表明排序時使用升序(true)還是降序(false)
// 該函數模板支援C++數組以及MFC集合CStringArray、CArray。
template <typename COLLECTION_TYPE, typename ELEMENT_TYPE>
void BubbleSort(COLLECTION_TYPE& collection, ELEMENT_TYPE element, int count, bool ascend = true)
{
  for (int i = 0; i < count-1; i++)
    for (int j = 0; j < count-1-i; j++)
      if (ascend)
      {
        // 升序
        if (collection[j] > collection[j+1])
        {
          ELEMENT_TYPE temp = collection[j];
          collection[j] = collection[j+1];
          collection[j+1] = temp;
        }
      }
      else
      {
        // 降序
        if (collection[j] < collection[j+1])
        {
          ELEMENT_TYPE temp = collection[j];
          collection[j] = collection[j+1];
          collection[j+1] = temp;
        }
      }
}
下列代碼對整型數組按升序排序:
  int arrayInt[] = {45, 23, 76, 91, 37, 201, 187};
  BubbleSort(arrayInt, arrayInt[0], 7);
下列代碼對整數集合按升序排序:
  CArray <int, int> collectionInt;
  collectionInt.Add(45);
  collectionInt.Add(23);
  collectionInt.Add(76);
  collectionInt.Add(91);
  collectionInt.Add(37);
  collectionInt.Add(201);
  collectionInt.Add(187);
  BubbleSort(collectionInt, collectionInt[0], collectionInt.GetSize());
下列代碼對一個字串數組按降序排序:
  CString arrayString[] = {"eagle", "hawk", "falcon"};
  BubbleSort(arrayString, arrayString[0], 3, false);

下列代碼對一個字串集合按降序排序:

CStringArray collectionString;
  collectionString.Add("eagle");
  collectionString.Add("hawk");
  collectionString.Add("falcon");
  BubbleSort(collectionString, collectionString[0], collectionString.GetSize(), false);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.