问题描述
我遇到的情况是,我希望有一个映射,该映射不允许在初始化后添加/删除键,但是允许更改值(因此,我不能简单地使映射const
).即
I have a situation, where I would like to have a map that does not allow to add/remove keys after initialization, but the values are allowed to change (thus I cannot simply make the map const
). Ie
/*semi-const*/ map<int,int> myMap = initMap();
myMap[1] = 2; // NOT OK, because potentially adds a new key
myMap.at(1) = 2; // OK, because works only if key is present
for (auto & element : myMap) {
element.second = 0; // OK, values may change
}
我可以为std::map
编写自己的包装器,但是我感觉这不太常见,所以我想知道是否已经存在解决方案.
I could write my own wrapper for std::map
, but I have the feeling that it is something not too uncommon, so I wonder if there is already an existing solution.
地图上是否有一些标准的习惯用法,不允许添加/删除键,而值可能会更改?
ps:我知道单独的标题有点含糊,因为键在地图中已经是const了,但是我希望我的意思很清楚...
ps: I know that the title alone is a bit vague, because the keys are already const in a map, but I hope it is clear what I mean...
推荐答案
是否可以创建一个包装器,该包装器包含允许在const
时更改该值的值并将其放在map
中?像这样:
Could you create a wrapper that contains the value that allows the value to be mutated when const
and put that in the map
instead? Something like:
template<typename T>
class Mutable {
mutable T value;
public:
const Mutable& operator=(const T& v) const { value = v; return *this; }
T& get() const { return value; }
};
然后您的地图可以是类型
Then your map can be of type
const std::map<int, Mutable<int>>
实时演示.
这篇关于映射与const键,但非const值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!