Reputation:
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;
}
}
Upvotes: 0
Views: 932
Reputation: 524
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
Upvotes: 2
Reputation: 34618
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.
Upvotes: 1
Reputation: 66371
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.
Upvotes: 2