检查unordered_maps的unordered_map是否包含密钥的最简单方法

use*_*112 26 c++ unordered-map c++11

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

my_map[k1][k2].

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

Cor*_*mer 33

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

my_map[k1][k2]
Run Code Online (Sandbox Code Playgroud)

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

相反,我更愿意使用std::unordered_map::find.因此,如果您确定第一个密钥存在,但不是第二个密钥存在

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

如果你想创建一个检查两个键是否存在的函数,那么你可以编写类似的东西

//------------------------------------------------------------------------------
/// \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;
}
Run Code Online (Sandbox Code Playgroud)


poo*_*a13 12

在 C++20 中,您可以使用该contains方法(如果我没记错的话,添加到所有关联容器中):

if (my_map.contains(k1) && my_map[k1].contains(k2))
{
    // do something with my_map[k1][k2]
}
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的缺点是“k1”搜索执行两次。更好的解决方案是对单个“k1”搜索的结果执行“k2”搜索。 (2认同)

Hui*_*Liu 7

您也可以使用counthttp://www.cplusplus.com/reference/unordered_map/unordered_map/count/

如果 key 不存在则返回 0


Yak*_*ont 5

template<class M>
bool contains(M const&){return true;}
template<class M, class K, class...Ks>
bool contains(M const&m, K const&k, Ks const&...ks){
  auto it=m.find(k);
  if (it==m.end()) return false;
  return contains(it->second, ks...);
}
Run Code Online (Sandbox Code Playgroud)

适用于每个单值关联容器。

contains(my_map, k1, k2)k1如果存在包含 的元素,则为 true k2