Skip to content

Latest commit

 

History

History
39 lines (30 loc) · 754 Bytes

File metadata and controls

39 lines (30 loc) · 754 Bytes

Snippets Snippets

Map with default value

Rational

a maps that’s returns a default value in case key is not found in the map.

#ifndef MAPDEFAULT_HPP
#define MAPDEFAULT_HPP

#include <map>

template<typename K, typename T, T DEFAULT_VALUE>
class MapDefault: public std::map<K, T>
{
public:
    MapDefault()
        : std::map<K, T>()
    {}

    MapDefault(const map<K, T>& base)
        : std::map<K, T>(base)
    {}

    const T& operator[](const K& key) const {
        auto it = find(key);
        if (it==this->end()) {
            static const T DEFAULT = DEFAULT_VALUE;
            return DEFAULT;
        } else {
            return it->second;
        }
    }
};

#endif // MAPDEFAULT_HPP