Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi.
we have a list of one class.
how to sort it by a variable as X ?( X is member of Class)
Posted
Updated 3-Dec-11 3:36am
v3

A) Do you need to write a sorting algorithm to do the sorting on the class member variable?

OR

B) Do you want to know how to sort the class in STL with a class member variable?


For either case, I would recommend writing a functor to help with the comparisons on your class member:

C++
struct CompareYourClassMemberXLess
{
  bool operator()(const YourClass &lhs, const YourClass &rhs)
  {
    // If they reference the same object, return false.
    // This will create a strict weak ordering.
    if (&lhs == &rhs)
      return false;

    return lhs.GetX() < rhs.GetX();
  }
};

// The declaration for the call to "GetX() const" will need to be declared with const.


Create an instance of your functor before you sort:
CompareYourClassMemberXLess CmpXLess;

Now in your sort algorithm, when you want to compare the two values in, you can call the varible CmpXLess like a function to determine where it fits in the search order.
YourClass a;
YourClass b;

CmpXLess(a,b);


for STL use it like this:

C++
std::sort(a.begin(), b.begin(), CompareYourClassMemberXLess());


BTW, feel free to change the obnoxiously long names to something that makes sense in your program. The names will not change the functionality.
 
Share this answer
 
Comments
Richard MacCutchan 4-Dec-11 12:43pm    
+5; I like your long names, they are very descriptive. And, this is one of the best explanations of functors that I've seen.
Try this will definitely help you...


http://www.dotnetperls.com/sort-list[^]
 
Share this answer
 
Comments
Philippe Mori 3-Dec-11 17:56pm    
Well, using LINQ to sort is effectively simpler to code...
fjdiewornncalwe 5-Dec-11 10:50am    
C++, not dotNet
 
Share this answer
 
Comments
Richard MacCutchan 3-Dec-11 12:07pm    
Sorry, missed link 3.
Richard MacCutchan 3-Dec-11 15:31pm    
Thanks.
But my type of list is a class.
And trying to sort it according to one of the variables that belong to the class.

On behalf of OP.
Philippe Mori 3-Dec-11 17:55pm    
There are overrides that allows to specify the function/interface to use for comparison.
Richard MacCutchan 4-Dec-11 3:19am    
I know that - the question is from the OP. If you have some information that would help then please reply to him/her.
Albert Holguin 4-Dec-11 1:45am    
Most of your links are .Net related, the question is tagged as C++.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900