简体   繁体   English

强制转换为 bool 是检查是否存在与键匹配的 unordered_map 值的有效方法吗? C++

[英]Is casting to a bool a valid way to check for the existence of a unordered_map value matching a key? c++

I have a nested unordered_map and would like to check whether a value has been created for a set of keys.我有一个嵌套的 unordered_map,想检查是否为一组键创建了一个值。 Most of the solutions online like this suggest iterating through the keys to check for their existence.这样的大多数在线解决方案都建议迭代密钥以检查它们的存在。 Is there an inherent problem with trying to access them and cast them to bool as I've done below?尝试访问它们并将它们转换为 bool 是否存在固有问题,就像我在下面所做的那样? The output from the test leads me to believe it works.测试的输出让我相信它有效。

    std::unordered_map<int, std::unordered_map<int, const char*>> myMap;
    myMap[1][2]="abc";
    myMap[2][2]="false";
    std::cout <<(bool)myMap[1][2]<< std::endl;
    std::cout <<(bool)myMap[0][0]<< std::endl;
    std::cout <<(bool)myMap[0][0]<< std::endl;
    std::cout <<(bool)myMap[1][4]<< std::endl;
    std::cout <<(bool)myMap[2][2]<< std::endl;

Output输出

1
0
0
0
1

Invoking operator[] on a non-const std::(unordered_)map will create the requested element with a default value if it does not already exist, before then returning a reference to that element.在非常量std::(unordered_)map上调用operator[]将创建具有默认值的请求元素(如果该元素尚不存在),然后返回对该元素的引用。 You are using that exact functionality when populating the [1][2] and [2][2] elements.在填充[1][2][2][2]元素时,您正在使用该确切功能。

Your output contains 0's because you are requesting keys that do not exist, so the map s are inserting those elements with default values, thus you end up with a null char* pointer that you are type-casting to bool .您的输出包含 0,因为您正在请求不存在的键,因此map插入具有默认值的元素,因此您最终会得到一个空char*指针,您将其类型转换为bool Any non-null value is output as true/1, and any null value is output as false/0.任何非空值输出为 true/1,任何空值输出为 false/0。

To simply check if an element exists, you can use the map's find() or count() method, or in C++20 the contains() method, eg:要简单地检查元素是否存在,您可以使用地图的find()count()方法,或者在 C++20 中使用contains()方法,例如:

bool keysExist(
    const std::unordered_map<int, std::unordered_map<int, const char*>> &m,
    int index1, int index2)
{
    auto iter = m.find(index1);
    return (iter != m.end()) && (iter->find(index2) != iter->end());
    // or: return (iter != m.end()) && (iter->count(index) == 1);
    // or: return (iter != m.end()) && iter->contains(index2);
}

std::unordered_map<int, std::unordered_map<int, const char*>> myMap;
myMap[1][2] = "abc";
myMap[2][2] = "false";

std::cout << keysExist(myMap, 1, 2) << std::endl;
std::cout << keysExist(myMap, 0, 0) << std::endl;
std::cout << keysExist(myMap, 0, 0) << std::endl;
std::cout << keysExist(myMap, 1, 4) << std::endl;
std::cout << keysExist(myMap, 2, 2) << std::endl;

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

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