c++ list sorting
-
I have a class A and it has x,y and z integer attributes I have created a list sequence container which has a type A list alist I want to sort the elements in this list according to y value. How can i do that? alist.sort() only sorts the elements according to the first attribute defined in the constructor.
-
I have a class A and it has x,y and z integer attributes I have created a list sequence container which has a type A list alist I want to sort the elements in this list according to y value. How can i do that? alist.sort() only sorts the elements according to the first attribute defined in the constructor.
You have a number of options. The first is to define an
operator <
for your class:bool operator<(const A &lhs, const A &rhs)
{
return lhs.y < rhs.y;
}You would make it a
friend
ofclass A
if it needs access toprivate
members of the class. Another option is to define a predicate function and pass it to thestd::list<...>::sort
function. This option would enable you to have multiple sort orders. Example:class A
{
// ...Stuff missing...
public:
static bool SortByYPred(const A &lhs, const A &rhs)
{
return lhs.y < rhs.y;
}
// ...Stuff missing...
};Now call
std::list<...>::sort
like this:alist.sort(&A::SortByYPred);
mehmetned wrote:
alist.sort() only sorts the elements according to the first attribute defined in the constructor.
The constructor has nothing to do with sort order.
Steve