Re: Sorting a CObArray?
From: Adrian Gibbons (adriangibbons_at_yahoo.co.uk)
Date: 03/27/04
- Next message: Steve Russell: "Re: GetModuleFileName"
- Previous message: Bob Moore: "Re: HotKey or ... ???"
- In reply to: Nathan Holt: "Re: Sorting a CObArray?"
- Messages sorted by: [ date ] [ thread ]
Date: 27 Mar 2004 11:07:25 -0800
Thanks for your replies. I've actually found a solution to my problem
from a posting back in 1997:
Google Groups link: http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=01bc7518%248dac3770%248adffe26%40tthomaspc
From: H. Tom Thomas (tthomas@seabase.com)
Subject: Re: sorted array
Newsgroups: microsoft.public.vc.mfc
Date: 1997/06/09
(EDITED)
Here is some code that does the trick. Derive a class from CObArray
with a
pure virtual function that you implement based on the attribute you
want to
sort.
// SortObArray.h
class CSortObArray : public CObArray
{
DECLARE_DYNAMIC(CSortObArray)
public:
CSortObArray();
void Sort();
private:
virtual BOOL CompareAndSwap(int pos) = 0;
};
// SortObArray.cpp
#include "stdafx.h"
#include "SortObArray.h"
IMPLEMENT_DYNAMIC(CSortObArray, CObArray)
CSortObArray::CSortObArray() : CObArray()
{
}
// Sort
void CSortObArray::Sort()
{
BOOL bNotDone = TRUE;
while (bNotDone)
{
bNotDone = FALSE;
for(int pos = 0;pos < GetUpperBound();pos++)
bNotDone |= CompareAndSwap(pos);
}
}
// CompareAndSwap write this according to your needs
BOOL CSortObArray_DerivedClass::CompareAndSwap(int pos)
{
CObject* temp;
int posFirst = pos;
int posNext = pos + 1;
if(((CSomeObj*)GetAt(posFirst))->m_sKey.CompareNoCase(((CSomeObj*)GetAt(posNext))->m_sKey)
> 0)
{
temp = GetAt(posFirst);
SetAt(posFirst, GetAt(posNext));
SetAt(posNext, temp);
return TRUE;
}
return FALSE;
}
For my implementation of CompareAndSwap() I've replaced "CSomeObj*"
with "CStringArray*" and "m_sKey" with "GetAt(0)" to compare the first
CString in the CStringArrays. I also moved the "CObject* temp" into
the IF structure and replaced it with "CStringArray* temp =
(CStringArray*)GetAt(posFirst)".
Due to the time pressures on my project and the fact that I do not
know STL already, this is a good enough solution for me. Maybe I'll
have a look at doing it using vectors and the STL in the future.
Hope this is of some help to people of the future :)
Adrian.
- Next message: Steve Russell: "Re: GetModuleFileName"
- Previous message: Bob Moore: "Re: HotKey or ... ???"
- In reply to: Nathan Holt: "Re: Sorting a CObArray?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|