On 8/26/2010 11:22 AM, Rick wrote:
> Thank you, John. This helps. But how do I create a class around this
> so I can add my own procedures? I need to format and display the
> elements in my structure, sort on various fields, search for a node
> by field, etc.
>
> I can crate my class, but don't know how to setup the constructor to
> create a new instance of my class with the std::list as the base object.
>
> And, yes, I'm still thinking in C I guess.
>    

There are a few ways to use the data structures. Normally, you don't 
need to subclass the STL containers. You either manipulate them directly 
in your code, or use algorithms that take iterators.

If you want to format and display elements, that really depends on the 
output. Is this going into a GUI? Command line? File? There are multiple 
ways to do this. For example, you could have a function that takes two 
iterators and a reference to a GUI list box and inserts elements 
returned by the first iterator in an implementation-specific manner 
until the iterator equals the second one. Using iterators also decouples 
your code from a specific container implementation. Maybe a vector would 
be better in some cases, especially where you know you have X elements, 
that won't change after construction, and you need random access. Using 
iterators means you just plug in the new container and go, and don't 
need to update references in your code to the specific container 
implementation.

If you want to sort on "various" fields, you have two options. If the 
sort order is static, write comparison functions (operator== and 
operator<) for your struct/class. Then you can plug it into the standard 
library algorithms that do sorting. If you need to sort on different 
fields at different times that is more complex. I recommend still having 
a "default" sort order based on the comparison functions, but define 
algorithms that takes iterators for your class and sort on different 
fields. Maybe have functions in the class that are not operator 
overloads but do the sorting, to keep the code close to the variables 
encapsulated in your class (good OOP design principle). Then your 
algorithm calls those functions.

Maybe looking up topics such as iterators, algorithms, and possibly 
functors would help. Don't try to use a C++ data structure in a C 
manner: it will work, but you will just create more work and get 
frustrated. Here are some links that might help:

http://www.cplusplus.com/reference/algorithm/
http://www.cprogramming.com/tutorial/stl/iterators.html

-- 
John Gaughan
http://www.johngaughan.net/

Reply via email to