拥有 std::map 的最佳方式,如果没有密钥,我可以在其中定义返回的内容?
Best way to have std::map where I can define what is returned if there is no key?
我正在使用 std::map 将一些 unsigned char 机器值映射到人类可读的字符串类型,例如:
std::map<unsigned char, std::string> DEVICE_TYPES = {
{ 0x00, "Validator" },
{ 0x03, "SMART Hopper" },
{ 0x06, "SMART Payout" },
{ 0x07, "NV11" },
};
我想对此进行修改,以便如果传递的密钥不存在,地图将 return "Unknown"。我希望调用者界面保持不变(即他们只是使用 [] 运算符从地图中检索他们的字符串)。最好的方法是什么?我在 Windows 7 上有 C++11。
您可以创建一些带有 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;
};
我正在使用 std::map 将一些 unsigned char 机器值映射到人类可读的字符串类型,例如:
std::map<unsigned char, std::string> DEVICE_TYPES = {
{ 0x00, "Validator" },
{ 0x03, "SMART Hopper" },
{ 0x06, "SMART Payout" },
{ 0x07, "NV11" },
};
我想对此进行修改,以便如果传递的密钥不存在,地图将 return "Unknown"。我希望调用者界面保持不变(即他们只是使用 [] 运算符从地图中检索他们的字符串)。最好的方法是什么?我在 Windows 7 上有 C++11。
您可以创建一些带有 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;
};