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