【问题标题】:How can I get around from using "[]" operator on const unordered_map in C++?如何在 C++ 中的 const unordered_map 上使用“[]”运算符?
【发布时间】:2020-12-11 12:27:03
【问题描述】:

我在下面有这个函数,wordcount_map 是一个 std::unordered_map <:string int> 类型。我正在使用 count 函数来查看键是否在地图中,以及是否要返回存储在该键处的值。但是,我收到一个错误,因为 map 被标记为 const 并且不允许使用 [] 运算符。请指教!

int lookupWithFallback(const StringIntMap& wordcount_map, const std::string& key, int fallbackVal) {

  if (wordcount_map.count(key)){
    return wordcount_map[key];
  }
  else {
    return fallbackVal;
  }
}

【问题讨论】:

    标签: c++ unordered-map


    【解决方案1】:

    使用 const 方法“find”: https://en.cppreference.com/w/cpp/container/unordered_map/find

    在你的情况下,类似:

    int lookupWithFallback(const StringIntMap& wordcount_map, const std::string& key, int fallbackVal) {
         auto it = wordcount_map.find(key);
         if(it != wordcount_map.end())
            return it->second;
         else
           return fallbackVal;
    }
    

    运算符 [] 不是 const,因为如果键不存在,它将被创建。 https://en.cppreference.com/w/cpp/container/unordered_map/operator_at

    【讨论】:

    • 请不要链接到 cplusplus.com。它被认为是错误的,经常过时并且通常会鼓励不良的编码实践。
    • 这里有一个更好的参考网站:en.cppreference.com/w/cpp/container/unordered_map/find
    • @bitmask 好的,谢谢,我不知道。我会修改它。
    【解决方案2】:

    使用find member function

    int lookupWithFallback(const StringIntMap& wordcount_map, 
                           const std::string& key, 
                           int fallbackVal) 
    {
        auto it = wordcount_map.find(key);
        return it != wordcount_map.end() ? it->second : fallbackVal; 
    }
    

    此方法也只会进行一次查找,即使您确实想修改地图也很有用。

    【讨论】:

      【解决方案3】:

      即使如果您的地图是非常量的,您的算法也需要冗余查找。

      您可以按照其他答案中的建议使用std::unordered_map::find

      int lookupWithFallback(const StringIntMap& wordcount_map, const std::string& key, int fallbackVal) {
          if (auto const it = wordcount_map.find(key); it != wordcount_map.end()) {
            return it->second;
          } else {
            return fallbackVal;
          }
      }
      

      或者您可以使用std::unordered_map::at 并捕获异常而不是传递fallbackVal

      try {
        return wordcount_map.at(key);
      } catch (std::out_of_range const& oor) {
        /* handle error in a sensible way or: */
        return fallbackVal;
      }
      

      对于比int 更复杂的类型,传递默认值是一个问题,因此您可能需要考虑将不存在的值作为错误处理。但是,不应将异常用于预期的情况。这取决于您的设置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多