TITLE: finding list elements using STL

(Newsgroups: comp.lang.c++, 8 Jun 98)


PAYBACK: payback@pe.net

> I'm using the STL list class to insert Node* 's  that have several
> fields.  I want to use find()  to search for the Node with the
> particular field ( or key) .
> 
> In other words, I have a list of Node *  (node pointers) . Each Node
> has several fields ( for example: the node-ID ).  I'm trying to use
> find() so that it can return the position of the Node with the  ID I
> need.   Is this possible?


PLAUGER: "P.J. Plauger" <pjp@dinkumware.com>

You need to use find_if instead. The third argument is the predicate
(function pointer or functoid) that gives you the boolean result you're
looking for. Shooting from the hip (I haven't tested this):

bool check_abc(nodetype *p)
	{return strcmp(p->key, "abc") == 0; }
.....
itr = find_if(NL.begin(), NL.end(), &check_abc);

If this works the way you want it to, then the proper solution is
to make a functoid that stores the key:

class check_key {
	const char *key;
public:
	check_key(const char *key_arg)
		: key(key_arg) {}
	bool operator()(nodetype *p)
		{return strcmp(p->key, key) == 0; }
	};
.....
itr = find_if(NL.begin(), NL.end(), check_key("abc"));

Then you should give serious thought about turning those C-style
strings into string objects, so you don't have to worry about the
lifetimes of keys.

Hope this helps (and that I haven't made too many mistakes).


