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

Sea*_*abs 2 c++ stdmap std visual-c++ c++11

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

std::map<unsigned char, std::string> DEVICE_TYPES = {
    { 0x00, "Validator" },
    { 0x03, "SMART Hopper" },
    { 0x06, "SMART Payout" },
    { 0x07, "NV11" },
};
Run Code Online (Sandbox Code Playgroud)

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

Edg*_*jān 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;
};
Run Code Online (Sandbox Code Playgroud)

wandbox示例