简体   繁体   中英

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...

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM