glob2-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [glob2-devel] question about std::list


From: Bradley Arsenault
Subject: Re: [glob2-devel] question about std::list
Date: Wed, 2 May 2007 20:45:40 -0400

On 5/2/07, Leo Wandersleb <address@hidden> wrote:
hi

fighting to get a meaningful unit allocation i ran into a sort that doesn't 
sort:
ok it sorted. but it sorted pointers. not what i thought it would sort.

ok now that i know and that it works, can someone tell me how to do it clean?

i had
unitsWorking.sort();
with
public:
Sint32 score;
bool operator < (const Unit& u) { return score < u.score; }
in Unit.h
and that was only sorting adresses.

i found out that:
class Predicate
{
        public:
        bool operator() (const Unit* lhs, const Unit* rhs) {
                return lhs->score < rhs->score;
        }
};
and then
unitsWorking.sort(Predicate());
worked as expected. But how can i tell it to use my operator <??

thanx for input

Leo Wandersleb

P.S.: Unit Alocation still is fun to work at although i'm not too impressd by my
success :/

Agreed, use std::list::sort rather than std::sort as it has a
customized algorithm.

Second of all, you need to pass in the function,somehow. Just calling
unitsWorking.sort() will sort the data in unitsWorking, which is
sorting the pointers, as you so described.

Making a  bool operator < (const Unit& u) { return score < u.score; }
in Unit.h won't work either, because the data in the list are
pointers, Unit*, not references, Uint& or Unit. Doing a comparison
function in unit.h that operates with pointers won't work either, as
its still not qualified.

From my learnings, the only truly clean way to sort a list of pointers
based on the pointers contents, rather than the pointer itself, is
through a predicate as follows:


template<typename t1> pointerCompare(t1* lhs, t1* rhs) { return (*lhs)
< (*rhs); };
and passing that into sort like:
unitsWorking.sort(pointerCompare<Unit>);

Thats about as clean as possible, although a more meaningfull name
than pointerCompare may be nesseccarry.



--
Really. I'm not lieing. Bradley Arsenault.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]