The CList and CStringList classes confuse me every time I use them and I have to look up what is actually happening. So here is an explanation for my own use, and yours too I hope.
This applies to CList as well, but I'll stick to CStringList for ease of illustration
When you AddHead to an empty list, then make further calls to AddHead the list grows like this:
I often make lists I want to consume in the order I created them in. To do that, after creating the list I call GetTail() and then RemoveTail().
Here is how to loop over the list in forward or backward order:
CStringList StringList ;
StringList.AddHead("Bob");
StringList.AddHead("Carol");
StringList.AddHead("Ted");
{
gLogger.Printf(ekLogMsg, "In order of creation:");
POSITION pos = StringList.GetTailPosition();
while (pos) {
gLogger.Printf(ekLogMsg, "<%s>", StringList.GetAt(pos).GetString());
StringList.GetPrev(pos);
}
}
{
gLogger.Printf(ekLogMsg, "In reverse order of creation:");
POSITION pos = StringList.GetHeadPosition();
while (pos) {
gLogger.Printf(ekLogMsg, "<%s>", StringList.GetAt(pos).GetString());
StringList.GetNext(pos);
}
}
The output looks like this:
In order of creation:
<Bob>
<Carol>
<Ted>
In reverse order of creation:
<Ted>
<Carol>
<Bob>
Hope this helps both me and you.
No comments:
Post a Comment