Skip to content

Instantly share code, notes, and snippets.

@opparco
Created July 22, 2023 18:09
Show Gist options
  • Save opparco/34e7c0c2bea021c133500da9493b18cc to your computer and use it in GitHub Desktop.
Save opparco/34e7c0c2bea021c133500da9493b18cc to your computer and use it in GitHub Desktop.
template<typename Key, typename T, T value = T()>
class defaultable_map :
public std::unordered_map<Key, T>
{
public:
// inherit std::unordered_map constructors
using std::unordered_map<Key, T>::unordered_map;
T & operator[](const Key & key)
{
auto it = find(key);
if (it == end())
{
// insert default value
auto result = insert(std::make_pair(key, value));
it = result.first;
}
return it->second;
}
};
//
defaultable_map<char, int, -1> m;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment