stl list and find

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paresh Patel

    stl list and find

    Hi,

    I have a list of Point pointer like,

    list<Point *> ptList;

    now if I want to find the Point that has some unique id, how do i do it?

  • Adam Fineman

    #2
    Re: stl list and find

    Paresh Patel wrote:[color=blue]
    > Hi,
    >
    > I have a list of Point pointer like,
    >
    > list<Point *> ptList;
    >
    > now if I want to find the Point that has some unique id, how do i do it?
    >[/color]

    Use find_if(), as below:


    #include <list>
    #include <cassert>
    #include <algorithm>
    #include <functional>

    using namespace std;

    class Point
    {
    public:
    Point(int id, int x, int y)
    : d_id(id), d_x(x), d_y(y)
    {}

    int get_id() const
    {
    return d_id;
    }

    private:
    int d_id;
    int d_x;
    int d_y;
    };


    struct equal_id : public binary_function <Point*, int, bool>
    {
    bool
    operator()(cons t Point* pp, int i) const
    {
    return pp->get_id() == i;
    }
    };


    struct delete_object
    {
    template<typena me T>
    void operator()(cons t T* ptr) const
    {
    delete ptr;
    }
    };


    int
    main()
    {
    list<Point*> lpp;

    for (int i = 1; i <= 10; ++i)
    {
    Point* pp = new Point(i, i, i);
    lpp.push_back(p p);
    }

    int to_find = 5;

    list<Point*>::i terator result = find_if(lpp.beg in(), lpp.end(),
    bind2nd(equal_i d(), to_find));

    assert((result != lpp.end()) &&
    ((*result)->get_id() == to_find));

    for_each(lpp.be gin(), lpp.end(),
    delete_object() );

    return 0;
    }

    HTH,

    - Adam


    --
    Reverse domain name to reply.

    Comment

    Working...