在 MFC 專案開發中,常需對 CStringArray、CArray 等集合類別進行排序。雖然 STL std::sort 功能強大,但存在兩大痛點:
GetData() 取得指標繞過封裝,但違反物件導向原則。為此設計一個輕量級排序函數模板 BubbleSort,採用氣泡排序演算法,雖非最佳時間複雜度,但對中小型資料集足夠實用,並完美支援 C++ 陣列與 MFC 集合。
template <typename COLLECTION_TYPE, typename ELEMENT_TYPE>
void BubbleSort(COLLECTION_TYPE& collection, ELEMENT_TYPE element, int count, bool ascend = true)
參數說明:
collection:支援 operator[] 的集合物件(C++ 陣列、CArray、CStringArray 等)element:僅用於推導元素型別,建議傳入 collection[0]count:元素個數ascend:true 升序(預設),false 降序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]) swap(...); // 升序
} else {
if (collection[j] < collection[j+1]) swap(...); // 降序
}
透過 ascend 旗標控制比較方向,單一函數滿足雙向排序需求,無需額外比較函數。
// C++ int 陣列升序
int arr[] = {45, 23, 76, 91, 37, 201, 187};
BubbleSort(arr, arr[0], 7);
// CArray<int> 升序
CArray<int, int> coll;
coll.Add(45); coll.Add(23); ...
BubbleSort(coll, coll[0], coll.GetSize());
// CString 陣列降序
CString strArr[] = {"eagle", "hawk", "falcon"};
BubbleSort(strArr, strArr[0], 3, false);
// CStringArray 降序
CStringArray strColl;
strColl.Add("eagle"); strColl.Add("hawk"); ...
BubbleSort(strColl, strColl[0], strColl.GetSize(), false);
std::sort。這個自製模板展示了「恰到好處」的工程思維:不追求大而全,精準解決特定場景痛點,是 MFC 專案中實用的排序利器。