简体   繁体   English

如何在STL容器中查找特定对象

[英]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. 我想在std :: list中找到一个特定的对象,其中该对象的属性遇到一个输入参数。

I found a solution using a unary predicate with find(.) or find_if(.) but in I need a binary function. 我找到了使用带有find(。)或find_if(。)的一元谓词的解决方案,但是我需要一个二进制函数。

Why can't I just let the iterator be the reference of the object (like java) and check the field via the reference? 为什么不能只让迭代器作为对象的引用(如java),然后通过引用检查字段? Is there a way to do that without using find/find_if... 有没有一种方法可以不使用find / find_if ...

I found a solution using a unary predicate with find(.) or find_if(.) but in I need a binary function. 我找到了使用带有find(。)或find_if(。)的一元谓词的解决方案,但是我需要一个二进制函数。

No – you do need a unary predicate – after all, the find_if function only compares with one object (the current object in the list). 不,您确实需要一元谓词–毕竟, find_if函数仅与一个对象(列表中的当前对象)进行比较。 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 : 现在您可以调用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? 为什么不能只让迭代器作为对象的引用(如java),然后通过引用检查字段?

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. 但是,当然,如果您一次只检查一个对象,我看不到为什么需要一个二进制谓词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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