Microsoft KB Archive/120961

= HOWTO: How to Sort a CStringArray in MFC =

Article ID: 120961

Article Last Modified on 11/21/2006

-

APPLIES TO

 Microsoft Foundation Class Library 4.2, when used with:  Microsoft C/C++ Professional Development System 7.0

 Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.1</li></ul>

 Microsoft Visual C++ 4.0 Standard Edition</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q120961

<div class="summary_section">

SUMMARY
You can use the sample code in this article to sort a CStringArray object. The main function constructs a CStringArray object, adds elements to it, prints out the elements, calls the sort member function to sort it, and then prints the sorted elements. The sort function uses the Bubble Sort algorithm to sort the array and calls the CompareAndSwap function to compare each string and swap them if necessary.

<div class="moreinformation_section">

Sample Code
/* * Compile options needed: /MT */


 * 1) include <afx.h>
 * 2) include <iostream.h>
 * 3) include <afxcoll.h>

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; }

Additional query words: kbinf 7.00 1.00 1.50 2.00 2.10 2.50 3.00 4.00 kbNoUpdate

Keywords: kbhowto kbcode KB120961

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.