简体   繁体   中英

How can I get around from using "[]" operator on const unordered_map in C++?

I have this function below with wordcount_map being an std::unordered_map <std::string, int> type. I'm using the count function to see if the key is in the map and if it is to return the value stored at that key. However, I'm getting an error because map is marked as const and [] operator is not allowed. Please advise!

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

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

Use the method "find" which is const: https://en.cppreference.com/w/cpp/container/unordered_map/find

In your case, something like:

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;
}

The operator [] is not const because if the key doesn't exist, it will be created. https://en.cppreference.com/w/cpp/container/unordered_map/operator_at

Use the 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; 
}

This method will also only do one lookup, and can be useful even when you do want to modify the map.

Even if your map were non-const, your algorithm requires a redundant lookup.

You can either use std::unordered_map::find as suggested in other answers:

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;
    }
}

or you can use std::unordered_map::at and catch an exception instead of passing a fallbackVal :

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

Passing default values is a problem for types more complicated than int so you may want to consider handling a non-existent value as an error. However, exceptions should not be used for expected cases. This depends on your setting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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