James Kanze
11/1/2008 8:39:00 AM
On Oct 31, 9:58 pm, mrc2...@cox.net (Mike Copeland) wrote:
> > > I'm confused about how to sort a list on an element of the list's
> > > structure. Here is my data definition:
> > > struct Finishes // computed Finish information
> > > {
> > > long netTime;
> > > int bibNumber;} fWork;
> > > typedef list<Finishes> FINISHES;
> > > FINISHES finishInfo;
> > > list<Finishes>::iterator fIter;
> > > I have populated the list successfully, and now I want to
> > > sort the list on the netTime element. All examples of the
> > > list.sort I've found work only with scalars or
> > > single-element structures. How do I do this with my data?
> > > TIA
> > Why not use an appropriate container like std::map where
> > netTime is the key and the integer its values? Elements are
> > then sorted on insertion using the default comparator
> > less<>.
> I don't have a need for that. My application just produces
> Times & assigns them to bibNumbers; I just need a dynamic
> array of such data (a list is fine), and then I sort the data
> on Time. I don't need to access any object members randomly,
> because once I've sorted the array I will process all objects
> in that sequence.
Actually, unless you need to insert at random locations in the
middle, std::vector or std::deque are probably more appropriate;
I'd probably go with std::vector in your case, since you can do
all your insertions at the end. std::map and std::set become
interesting when you have to maintain order with ongoing
insertions.
Anyway, as others have probably already said (I haven't seen the
other responses), all you need is to define the appropriate
comparator. Something like:
struct CompareTimes
{
bool operator()(
Finishes const& lhs,
Finishes const& rhs ) const
{
return lhs.netTime < rhs.netTime ;
}
} ;
and pass an instance of this to the appropriate sort routine.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34