Rn2dy
Rn2dy

Reputation: 4190

How to find a specific object in a STL container

I want to find a specific object in a std::list where the object's attribute meets an input argument.

I found a solution using a unary predicate with find(.) or find_if(.) but in I need a binary function.

Why can't I just let the iterator be the reference of the object (like java) and check the field via the reference? Is there a way to do that without using find/find_if...

Upvotes: 0

Views: 2855

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 546093

I found a solution using a unary predicate with find(.) or find_if(.) but in I need a binary function.

No – you do need a unary predicate – after all, the find_if function only compares with one object (the current object in the list). Your predicate needs to know which attribute value to compare with:

struct compare_with {
    int attr_value;
    compare_with(int attr_value) : attr_value(attr_value) { }

    bool operator ()(your_object const& obj) const { return obj.attr == attr_value; }
};

Now you can invoke find_if:

result = find_if(your_list.begin(), your_list.end(), compare_with(some_value));

Why can't I just let the iterator be the reference of the object (like java) and check the field via the reference?

You can. But it’s absolutely not clear what you mean by this. Just iterate over the list.

Upvotes: 8

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

Yes, you can do that:

list<myclass>::iterator i;
for(i = mylist.begin(); i != mylist.end(); ++i)
{
    if(i->field == value_to_check_for)
        break;
}

// now i is an iterator pointing to the object if it was found
// or mylist.end() if it wasn't

But of course, I can't see why you'd need a binary predicate if you're just checking one object at a time.

Upvotes: 2

Related Questions