Created
July 22, 2023 18:09
-
-
Save opparco/34e7c0c2bea021c133500da9493b18cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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