TITLE: how to sort a std::list of pointers (Newsgroups: comp.lang.c++, comp.lang.c++.moderated, 27 Jan 2000) KULKARNI: "Yogesh Kulkarni" > I have a std::list of pointers to foo, where foo is my class. Because > I want to sort the list based on some member of foo, I provided > operator< in the foo, which I thought, would enable the sorting. What > I found out later is that the list was not getting sorted based on > the foo's data member values. It was in fact gettng sorted on the > memory addresses where the pointers in the list were allocated. I am > sure, this technique does work on list of solid objects, but is > apparently not appropriate for the list of pointers. The question is, > how can I provide a custom sort mechanism that enables me to sort the > list of pointers based on the values of objects that are pointed to > by the pointers. ADLER: Darin Adler You need to define a function object. Here's how I'd do it. template struct LessByPointedToValue : std::binary_function { bool operator()(T const * x, T const * y) const { return std::less()(*x, *y); } }; // ... std::list fl; // ... fl.sort(LessByPointedToValue()); // ... The call to sort passes a function object, an instance of the class, which is an instance of the class template LessByPointedToValue. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com