有std :: map的最佳方法,如果没有密钥,我可以定义返回的内容吗?

时间:2017-01-25 18:15:14

标签: c++ c++11 visual-c++ std stdmap

我使用std :: map将一些unsigned char机器值映射到人类可读的字符串类型,例如:

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

我想修改它,以便如果传递的密钥不存在,地图将返回&#34;未知&#34;。我希望调用者接口保持不变(即他们只是使用[]运算符从地图中检索它们的字符串)。最好的方法是什么?我在Windows 7上有C ++ 11。

1 个答案:

答案 0 :(得分:7)

您可能会创建一些包含 operator [] 的包装器以提供所需的行为:

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