检查unordered_maps的unordered_map是否包含密钥的最简单方法 [英] Simplest method to check whether unordered_map of unordered_maps contains key

查看:82
本文介绍了检查unordered_maps的unordered_map是否包含密钥的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用unordered_maps的unordered_map,这样我就可以使用多键"语法引用元素:

I am using an unordered_map of unordered_maps, such that I can reference an element using the "multi key" syntax:

my_map [k1] [k2] .

是否存在使用相同的多键"语法在尝试访问元素之前检查它是否存在的简便方法?如果没有,最简单的方法是什么?

Is there a convenient way to use the same "multi-key" syntax to check whether an element exists before trying to access it? If not, what is the simplest way?

推荐答案

如果您打算测试密钥的存在,则不会使用

If your intention is to test for the existence of the key, I would not use

my_map[k1][k2]

因为 operator [] 将如果该键尚不存在,则默认为其构造一个新值.

because operator[] will default construct a new value for that key if it does not already exist.

我宁愿使用 std :: unordered_map :: find .因此,如果您确定第一个密钥存在,但是第二个则不可以

Rather I would prefer to use std::unordered_map::find. So if you are certain the first key exists, but not the second you could do

if (my_map[k1].find(k2) != my_map[k1].end())
{
    // k2 exists in unordered_map for key k1
}

如果您要创建一个检查两个键是否存在的函数,则可以编写类似

If you would like to make a function that checks for the existence of both keys, then you could write something like

//------------------------------------------------------------------------------
/// \brief Determines a nested map contains two keys (the outer containing the inner)
/// \param[in] data Outer-most map
/// \param[in] a    Key used to find the inner map
/// \param[in] b    Key used to find the value within the inner map
/// \return True if both keys exist, false otherwise
//------------------------------------------------------------------------------
template <class key_t, class value_t>
bool nested_key_exists(std::unordered_map<key_t, std::unordered_map<key_t, value_t>> const& data, key_t const a, key_t const b)
{
    auto itInner = data.find(a);
    if (itInner != data.end())
    {
        return itInner->second.find(b) != itInner->second.end();
    }
    return false;
}

这篇关于检查unordered_maps的unordered_map是否包含密钥的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆