Hi, I'm having trouble figuring how to search for a specific element of a class in a list.
I saw some examples of find() but they only show how to search for a string or an int.
Another thing is modifying elements of a class. So let's say I have this:

class A{
int ID;
string name;
}

So if I make a list full of A objects how do I use find() to search for the object that has the ID 'X' so I would be able to change the name to 'Y'? Is there an easy solution or should I make my own list?

Recommended Answers

All 2 Replies

You can implement operator== for your class, or alternatively use find_if, which takes a predicate:

#include <algorithm>
#include <functional>

struct id_match: public binary_function<A, int, bool> {
    bool operator()(const A& obj, int id) const { return obj.ID == id; }
};

//...

match = find_if(l.begin(), l.end(), bind2nd(id_match(), 999));

A regular loop isn't out of the question either:

list<A>::iterator it = l.begin();

while (it != l.end() && it->ID != 999)
    ++it;

if (it != l.end())
    it->name = new_name;

Of course, in your example the data members of the class are private, so some kind of accessor will be needed.

Thanks for your reply, can you just explain what does the bind2nd means?

EDIT: nvm found it on c++ ref

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.