-
February 14th, 2003, 10:36 AM
#1
MFC STL: How can I sort a 'CArray' (or 'CStringArray', 'CIntArray', etc.)?
Q: How can I sort a 'CArray' (or 'CStringArray', 'CIntArray', etc.)?
A: If the CxxxArray's items can be compared, then use 'std::sort':
Ascending:
Code:
#include <algorithm>
CArray<int, int&> MyCArray;
CStringArray MyStringArray;
// Sort the CArray of ints
std::sort(MyCArray.GetData(), MyCArray.GetData() + MyCArray.GetSize());
// Sort the CStringArray
std::sort(MyStringArray.GetData(), MyStringArray.GetData() + MyStringArray.GetSize());
Descending:
You need to supply a comparison function.
Code:
#include <algorithm>
bool SortDescendingInt(const int& x, const int& y)
{
return x > y;
}
bool SortDescendingString(const CString& s1,
const CString& s2)
{
return s1 > s2;
}
CArray<int, int> MyCArray;
CStringArray MyStringArray;
// Sort the CArray of ints
std::sort(MyCArray.GetData(),
MyCArray.GetData() + MyCArray.GetSize(),
SortDescendingInt);
// Sort the CStringArray
std::sort(MyStringArray.GetData(),
MyStringArray.GetData() + MyStringArray.GetSize(),
SortDescendingString);
FAQ contributed by: [Paul McKenzie]
Last edited by Andreas Masur; July 24th, 2005 at 03:30 PM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|