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

list::sort with pointers

P: n/a
How do I define the use of list::sort() when the list holds pointers? For
example,

#include <list>

class foo {
public:
foo(int i): i(i) {};
~foo();

private:
int i;
};

void main() {
foo *f = new foo(3);
foo *g = new foo(2);

list< foo* > l;
l.push_back(f);
l.push_back(g);

l.sort(); // I want this to sort based on foo::i
}
Thanks,
Tim Partridge

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Wed, 13 Aug 2003 12:35:27 -0400
Tim Partridge <tj******@lassar.math.uwaterloo.ca> wrote:
How do I define the use of list::sort() when the list holds pointers?
For example,

#include <list>

class foo {
public:
foo(int i): i(i) {};
~foo();

private:
int i;
};

void main() {
foo *f = new foo(3);
foo *g = new foo(2);

list< foo* > l;
l.push_back(f);
l.push_back(g);

l.sort(); // I want this to sort based on foo::i
}


You can't call sort on a list with pointers. You have to specify a
sorting function: l.sort(someFunction);

br
socketd
Jul 19 '05 #2

P: n/a

"Tim Partridge" <tj******@lassar.math.uwaterloo.ca> wrote in message
news:Pi*************************************@lassa r.math.uwaterloo.ca...
How do I define the use of list::sort() when the list holds pointers? For
example,

#include <list>

class foo {
public:
foo(int i): i(i) {};
~foo();

private:
int i;
};

void main() {
foo *f = new foo(3);
foo *g = new foo(2);

list< foo* > l;
l.push_back(f);
l.push_back(g);

l.sort(); // I want this to sort based on foo::i
}
Thanks,
Tim Partridge


bool sort_func(foo* lhs, foo* rhs)
{
return lhs->i < rhs->i;
}

l.sort(sort_func);

Aside from the fact that i is private, that should work, but untested code.

john
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.