SeanLabs
SeanLabs

Reputation: 1839

Best way to have std::map where I can define what is returned if there is no key?

I am using a std::map to map some unsigned char machine values into human readable string types, e.g.:

std::map<unsigned char, std::string> DEVICE_TYPES = {
    { 0x00, "Validator" },
    { 0x03, "SMART Hopper" },
    { 0x06, "SMART Payout" },
    { 0x07, "NV11" },
};

I'd like to modify this so that if the key passed is not present, the map will return "Unknown". I want the caller interface to stay the same (i.e. they just retrieve their string from the map using the [] operator). What's the best way to do this? I have C++11 on Windows 7 available.

Upvotes: 2

Views: 72

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

You might create some wrapper with operator[] overloaded to provide the required behaviour:

class Wrapper {
public:
    using MapType = std::map<unsigned char, std::string>;

    Wrapper(std::initializer_list<MapType::value_type> init_list)
        : device_types(init_list)
    {}

    const std::string operator[](MapType::key_type key) const {
        const auto it = device_types.find(key);
        return (it == std::cend(device_types)) ? "Unknown" : it->second;
    }

private:
    const MapType device_types;
};

wandbox example

Upvotes: 7

Related Questions