#define _AFXDLL
#include <afx.h>
#include <afxcoll.h>
#include <iostream>
using namespace std;
class CSortStringArray : public CStringArray {
public:
void Sort();
private:
BOOL CompareAndSwap(int pos);
};
void CSortStringArray::Sort()
{
BOOL bNotDone = TRUE;
while (bNotDone)
{
bNotDone = FALSE;
for(int pos = 0;pos < GetUpperBound();pos++)
bNotDone |= CompareAndSwap(pos);
}
}
BOOL CSortStringArray::CompareAndSwap(int pos)
{
CString temp;
int posFirst = pos;
int posNext = pos + 1;
if (GetAt(posFirst).CompareNoCase(GetAt(posNext)) > 0)
{
temp = GetAt(posFirst);
SetAt(posFirst, GetAt(posNext));
SetAt(posNext, temp);
return TRUE;
}
return FALSE;
}
void main()
{
CSortStringArray sortArray;
sortArray.Add(CString("Zebra"));
sortArray.Add(CString("Bat"));
sortArray.Add(CString("Apple"));
sortArray.Add(CString("Mango"));
for (int i = 0; i <= sortArray.GetUpperBound(); i++)
cout << sortArray[i] << endl;
sortArray.Sort();
cout << endl;
for (int j = 0; j <= sortArray.GetUpperBound(); j++)
cout << sortArray[j] << endl;
system("pause");
}
参考: How to Sort a CStringArray in MFC
本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2008/06/03/1212853.html,如需转载请自行联系原作者