Tim Frink wrote:
Hi,
I need some help with STL lists.
I've a list with pointers to some objects,
let's say std::list< ObjectA* > myList.
The objects of the class ObjectA all have a
function "int getIntValue()". What I need
now is to sort all elements of "myList" by the
return value of "getIntValue()", i.e. after sorting
the first element in the list will be the one with
the smallest return value of "getIntValue()" ... and
the last obviously with the largest.
Could you give me some hints how to do that?
Regards,
Tim
As stated earlier you need a comparator function to use with
std::sort(). Myself I created a template to handle iterator type
comparisons like that below
template <typename T>
inline bool DRefCompare(T i1,T i2)
{
return *i1 < *i2;
}
class Compartment
{
public:
typedef std::vector<MyObject> vector;
typedef std::vector<vector::iterator> ivector;
typedef std::vector<vector::const_iterator> civector;
bool operator < (const MyObject &inp) const;
/*
Rest of the definition here
*/
};
MyObject::ivector viCmp;
/*
Other code here
Create sorted list of MyObject iterators
*/
MyObject::vector::iterator iC = vCmp.begin();
do
{
viCmp.push_back(iC);
}
while (++iC != vCmp.end());
std::sort(viCmp.begin(),viCmp.end(),&DRefCompare<MyObject::vector::const_iterator>);
Naturally this relies on the operator < () exists for type T, so changes
to make it more general might be more suitable
JB