0

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?

Edited by Swiftle: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Swiftle
1

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.

0

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

EDIT: nvm found it on c++ ref

Edited by Swiftle: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.