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

stl list and find

P: n/a
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?

Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Paresh Patel wrote:
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
--
Reverse domain name to reply.

Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.