By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,131 Members | 1,821 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,131 IT Pros & Developers. It's quick & easy.

sorting by name

Dorothy Dean
P: 2
How can i write a method that arranges objects from some class by name?
Jun 4 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
You mean the name is a data member??

If so, use the STL sort.

That will require that you write an operator< for your class so the sort can call it. The operator< returns true if the name in the first argument is less than the name in the second argument.

Expand|Select|Wrap|Line Numbers
  1. bool MyClass::operator<(MyClass& rhs);
  2.  
The above function returns true if this->name < rhs.name.

You can do the same thing without using a member function if the name is accessible by using some other class method.

Expand|Select|Wrap|Line Numbers
  1. bool CheckForLess(MyClass& lhs, MyClass& rhs);
  2.  
Here you access a GetName() method and do the compare. Then you pass the address of this function to the sort.

The underlying assumption is that the objects are in an STL container.

If this is not the case, then in addition to the compare, you have to write the sort from scratch.
Jun 4 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.