SKumar wrote:
I have a list which contains my class objects. My class is
having two variables. I want to sort the list based on these two
variables.
The first thing to do when you want to sort objects is to define
a [strict partial] ordering on them. For the case of your two
variables you probably could do with a lexicographical order as
you could obtain using tuples (either from TR1 or from Boost):
return tie(obj1.nAngle, obj1.nDist) < tie(obj2.nAngle, obj2.nDist);
'tie()' is a factory function creating a tuple of references and
the expression just returns the result of comparing the two created
tuples. The same effect can be obtained using appropriate logic to
compare the involved object but I consider the above much more
readable than manual alternative.
Once you have your ordering defined, you would next have to determine
how to apply the order. There are generally two possible approaches:
1. If the ordering always applies reasonably to the involved objects,
you can make the object available by overloading suitable
operators for the corresponding class. Effectively, this means
that you define 'operator<()' for objects for your class:
bool operator< (Type const& obj1, Type const& obj2) {
// e.g. the tuple expression goes here if the operator has
// appropriate access to the member variables
}
2. If the ordering is specific to the task at hand and is not really
related to the objects in general, you would rather use a
"predicate" which is just an object that can be used with the
function call operator on the involved objects. Such a predicate
can be a simple function (in which case the object is actually
just the function pointer) or a class, e.g.:
struct MyCompare {
bool operator()(Type const& obj1, Type const& obj2) const {
// comparing the objects goes here
}
};
With this in place, you could easily sort a random access sequence
of your objects using either the default predicate which happens to
be 'std::less<Type>' and simply uses 'operator<()', i.e.
std::sort(sequence.begin(), sequence.end());
or you can use the 'std::sort()' function specifying the predicate:
std::sort(sequence.begin(), sequence.end(), MyCompare());
If you really want to sort a 'std::list<Type>', you would use the
member 'sort()' because 'std::list<Type>' does not provide random
access iterators but can still be sorted efficiently.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence