list::sort with pointers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tim Partridge

    list::sort with pointers

    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

  • Socketd

    #2
    Re: list::sort with pointers

    On Wed, 13 Aug 2003 12:35:27 -0400
    Tim Partridge <tjpartri@lassa r.math.uwaterlo o.ca> wrote:
    [color=blue]
    > 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
    > }[/color]

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

    br
    socketd

    Comment

    • John Harrison

      #3
      Re: list::sort with pointers


      "Tim Partridge" <tjpartri@lassa r.math.uwaterlo o.ca> wrote in message
      news:Pine.SOL.4 .44.03081312243 60.5826-100000@lassar.m ath.uwaterloo.c a...[color=blue]
      > 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
      >[/color]

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

      l.sort(sort_fun c);

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

      john


      Comment

      Working...