简体   繁体   English

更新std :: map中键的值

[英]updating the value of a key in a std::map

Assume we have a simple structure such as the following 假设我们有一个简单的结构,如下所示

struct T{
  int x;
  int y;
};
T t1, t2;

Also assume that I have a map<T, int> myMap and that two structures of type T are compared using their x values only. 还假设我有一个map<T, int> myMap并且只使用它们的x值比较两个类型为T结构。 Ie t1 < t2 iff t1.x < t2.x . t1 < t2 iff t1.x < t2.x I am trying to update some of the y values of the keys over myMap. 我试图通过myMap更新键的一些y值。 This should not affect how the map is seeing the keys. 这不应该影响地图看到键的方式。 Is there any way other than removing the old element and inserting a new one? 除了删除旧元素和插入新元素之外还有什么方法吗?

If you are sure that y does not participate in the "logical state" of your class and is merely an implementation detail, then you could declare it mutable : 如果您确定y不参与类的“逻辑状态”并且仅仅是一个实现细节,那么您可以声明它是mutable

struct T
{
  int x;
  mutable int y;
  bool operator<(const T& rhs) const { return x < rhs.x; }
};

Now you ought to be able to change y : 现在你应该能够改变y

for (auto it = m.begin(); it != m.end(); ++it)
{
  it->first.y = -2; // ouch? But it won't invalidate the map's invariants.
}

No, map cannot let you modify the keys, because that could invalidate the map invariant (ordering of the elements) — you know it won't, but the map cannot know that, so it errs on the side of caution and disallows that. 不, map不能让你修改键,因为这可能使地图不变量无效(元素的排序) - 你知道它不会,但map不能知道,所以它在谨慎方面是错误的,并且不允许这样做。

Remove and reinsert is a proper way to do it. 删除并重新插入是一种正确的方法。 Treat keys as immutable. 将密钥视为不可变的。

如果y不参与比较,则可以将其标记为mutable ,因此即使值不变也可以修改它。

The keys of std::map are const. std::map的键是const。 So you cannot change it. 所以你无法改变它。

Also, if you use only x to compare the keys, then why do you std::map<T,int> ? 另外,如果你只使用x来比较键,那你为什么要std::map<T,int> Why not this: 为什么不这样:

std::map<int, std::pair<T,int> > data; //where keys would be t.x

After all, in your map, keys are effectively tx . 毕竟,在地图中,键实际上是tx

You can modify T::y if it does not affect comparison operator behaviour. 如果它不影响比较运算符行为,则可以修改T::y On the other hand it is bad style to modify map's key, it should be immutable. 另一方面,修改map键的样式很糟糕,它应该是不可变的。 Some implementations of Standard Library do allow to modify key. 标准库的某些实现允许修改密钥。

键在地图中是常量,尝试将新值复制到新地图中。

Like Cat said you shouldn't change keys for a lot of good reasons but you seem to know enough to move ahead. 就像Cat说的那样,你不应该出于很多好理由改变按键,但你似乎已经知道了足够的进展。

Cast away the key's constness with const_cast and you can't do all kinds of damage.... err changes. 用const_cast抛弃键的常量,你不能做各种各样的伤害......错误的改变。 Just double check that the comparison operator still returns the same after modifying it. 只需仔细检查比较运算符在修改后仍然返回相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM