简体   繁体   English

检查相同的列表元素是否包含真或假

[英]Check if same list element contains true or false

Let's say that I have a list std::list<MyClass> myList like this:假设我有一个像这样的列表std::list<MyClass> myList

ID      Valid
--------------
1000    true
1000    false
1000    true
2000    false
2000    false
3000    true
3000    true

And this boolean value comes from a function bool isExpired(MyClass &a) .而这个 boolean 值来自 function bool isExpired(MyClass &a)

How can I check if one group of elements have equal or different boolean values?如何检查一组元素是否具有相同或不同的 boolean 值? For example in this case 1000 should be false because second 1000 in list has false value.例如,在这种情况下 1000 应该是假的,因为列表中的第二个 1000 具有假值。

This is false这是假的

1000    true
1000    false //because of this
1000    true

This is false这是假的

2000    false
2000    false

This is true这是真实的

3000    true
3000    true

I tried to create a new map which will override the key and value.我试图创建一个新的 map 它将覆盖键和值。

std::map<long, bool> status;
for(const auto &it : myList)
{
   status[it.ID] = status[it.ID] || isExpired(it); 
}

But it does not work as expected.但它没有按预期工作。 It returns true for the element with an ID 1000.它为 ID 为 1000 的元素返回true

You don't want to use ||你不想使用|| , you want to use && , which means that you have to default to true: ,您想使用&& ,这意味着您必须默认为 true:

std::map<long, bool> status;
for(const auto &it : myList)
{
    auto entry = status.find(it.ID);
    if (entry != status.end()) {
        entry->second = entry->second && isExpired(it);
    } else {
        status[it.ID] = true;
    }
}

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

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