我正在使用 std::map 将一些 unsigned char 机器值映射到人类可读的字符串类型,例如:
std::map<unsigned char, std::string> DEVICE_TYPES = {
{ 0x00, "Validator" },
{ 0x03, "SMART Hopper" },
{ 0x06, "SMART Payout" },
{ 0x07, "NV11" },
};
我想对此进行修改,以便如果传递的 key 不存在, map 将返回“未知”。我希望调用者界面保持不变(即他们只是使用 [] 运算符从 map 中检索他们的字符串)。最好的方法是什么?我在 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;
};
关于c++ - 拥有 std::map 的最佳方法,如果没有 key ,我可以在其中定义返回的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858724/