stl list and find

P

Paresh Patel

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?
 
A

Adam Fineman

Paresh said:
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?

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()(const Point* pp, int i) const
{
return pp->get_id() == i;
}
};


struct delete_object
{
template<typename T>
void operator()(const 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(pp);
}

int to_find = 5;

list<Point*>::iterator result = find_if(lpp.begin(), lpp.end(),
bind2nd(equal_id(), to_find));

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

for_each(lpp.begin(), lpp.end(),
delete_object());

return 0;
}

HTH,

- Adam
 

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
474,148
Messages
2,570,838
Members
47,385
Latest member
Joneswilliam01

Latest Threads

Top