template <class C> void list::sort( C fn ) question

  • Thread starter Math Preregistration System
  • Start date
M

Math Preregistration System

I'm using a std::list as a container for some pointers to objects, for
example

list< C* > lst;

I would like to sort them using two different criteria, say first by
C.first and then by C.second. Is it possible to use template <class C>
void list::sort( C fn ) and define two different fns, and use them
something like

lst.sort< C >( sortOnFirst() );
lst.sort< C >( sortOnSecond() ):

or am I not on the right track? I don't understand exactly how this
works. Alternatively, I can use a vector and std::sort() if you can
convince me it would be a better idea, but the main point is that I need
to sort according to two different criteria.

Thanks for you input!
Tim Partridge
 
R

Rolf Magnus

Ron said:
You need to define sortOnFirst, you don't want to put the parens
there.

You do if you make them function objects.
You haven't give any clue as to the nature of C, but your functions
should look something like:
bool sortOnFirst(const C& left, const C& right) {
// return true if left is logically less than right in this
sorting order
// ...
}
lst.sort<C>(sortOnFirst)

Or:

struct sortOnFirst : public std::binary_function<C, C, bool>
{
bool operator()(const C& left, const C& right) const
{
// return true if left is logically less than right in this
sorting order
// ...
}
};

lst.sort(sortOnFirst());
 
R

Rolf Magnus

Klaus said:
inline bool sortOnFirst_then_Second(C* a, C* b)

Note that the inline keyword here doesn't provide any benefit, since the
function will be called through a pointer, which excludes the
possibility to expand the function inline. If you want that, you need a
function object.
 
R

Ron Natalie

Rolf Magnus said:
Note that the inline keyword here doesn't provide any benefit, since the
function will be called through a pointer, which excludes the
possibility to expand the function inline. If you want that, you need a
function object.

That and the objects it wants to pass to it are C's not C*'s.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top