如何使 unordered_map 仅适用于预定义的键?
How to make an unordered_map only work with predefined keys?
我如何创建一个 unordered_map
,它将只对我想要的键起作用,否则会抛出错误。
例如 python:
my_dict = {
'a': 0,
'b': 0
}
my_dict['c'] # Will raise an error
但在 C++ 中,等效代码将初始化 'c': 0
对。
怎么办?最明显的解决方案是在将密钥传递给地图之前检查密钥,但是对于大量密钥,它可能会变得很笨重 if
s.
but in c equivalent code will initialize 'c': 0 pair. What to do?
干脆不要使用operator[]
。
您可以改用 at
成员函数。它的行为类似于 pythons dict:
Returns: A reference to the mapped_type corresponding to x in *this
Throws: An exception object of type out_of_range if no such element is present.
或者,您可以使用 find
,其中 returns 元素的迭代器或元素不存在时结束的迭代器,而不是抛出异常。
如果您不想修改这些值,那么您可以将地图设为 const,这将阻止使用 operator[]
。
如果您想保持地图可修改,但不允许添加元素,那么您需要定义一个包装器 class,在私有成员中包含地图,并委托允许的操作。
使用 find
方法而不是取消引用运算符来访问 unordered_map。如果未找到项目,则返回 end
迭代器。
使用类型系统。用你想要的键定义一个 enum
,然后只使用枚举值而不是文字。
enum MyKeys { A, B };
std::unordered_map<MyKeys, int> my_map;
my_map.insert({A,0});
my_map.insert({B,1});
my_map.insert({C,0}); // compile time error
my_map.insert({'C',23}); // compile time error
my_map[A]; // works
my_map[C]; // compile time error
my_map[2]; // compile time error
我如何创建一个 unordered_map
,它将只对我想要的键起作用,否则会抛出错误。
例如 python:
my_dict = {
'a': 0,
'b': 0
}
my_dict['c'] # Will raise an error
但在 C++ 中,等效代码将初始化 'c': 0
对。
怎么办?最明显的解决方案是在将密钥传递给地图之前检查密钥,但是对于大量密钥,它可能会变得很笨重 if
s.
but in c equivalent code will initialize 'c': 0 pair. What to do?
干脆不要使用operator[]
。
您可以改用 at
成员函数。它的行为类似于 pythons dict:
Returns: A reference to the mapped_type corresponding to x in *this
Throws: An exception object of type out_of_range if no such element is present.
或者,您可以使用 find
,其中 returns 元素的迭代器或元素不存在时结束的迭代器,而不是抛出异常。
如果您不想修改这些值,那么您可以将地图设为 const,这将阻止使用 operator[]
。
如果您想保持地图可修改,但不允许添加元素,那么您需要定义一个包装器 class,在私有成员中包含地图,并委托允许的操作。
使用 find
方法而不是取消引用运算符来访问 unordered_map。如果未找到项目,则返回 end
迭代器。
使用类型系统。用你想要的键定义一个 enum
,然后只使用枚举值而不是文字。
enum MyKeys { A, B };
std::unordered_map<MyKeys, int> my_map;
my_map.insert({A,0});
my_map.insert({B,1});
my_map.insert({C,0}); // compile time error
my_map.insert({'C',23}); // compile time error
my_map[A]; // works
my_map[C]; // compile time error
my_map[2]; // compile time error