[英]C++ std::map adds values when key not found
I'm not very good with collections in C++ so go easy on me if my question is a bit Stupid. 我对C ++的收集不是很好,所以如果我的问题有点愚蠢,请对我轻松一点。
I'm currently having 2 maps 我目前有2张地图
map<int, Segment*> varSeg;
map<Segment*, bool> rules;
So varSeg is filled with an assignment of var -> Segment* objects and based on some logic I'm trying to fill in the rules map using something like the following loop. 因此varSeg充满了var-> Segment *对象的分配,并且基于某种逻辑,我试图使用类似以下循环的内容来填充规则映射。
for(...looping on some vars){
int segVar = getVar();
rules[varSeg[segVar]] = (segVar > 0);
}
However, if a certain segVar
wasn't already contained in varSeg
I encountered a weird behavior. 但是,如果某segVar
是不是已经包含在varSeg
我遇到了一个怪异的行为。 A new entry was created inside varSeg
map with key segVar
and a value of Null
for the Segment. 在varSeg
映射中创建了一个新条目, varSeg
包含键segVar
和Segment的值为Null
。 Which ofcourse caused all sorts of problems in my code later. 当然哪一个会在以后的代码中引起各种各样的问题。
My question is why did this happen? 我的问题是为什么会这样? isn't the varSeg[segVar]
statement here a read statement? 这里的varSeg[segVar]
语句不是读语句吗? This was very difficult to debug because I couldn't find a place in my code I was writing null values to the map. 这很难调试,因为我在代码中找不到位置,正在向地图写入空值。 So could you explain what I did wrong here? 那你能解释我在这里做错了什么吗?
My question is why did this happen? 我的问题是为什么会这样?
Because that's what std::map::operator[]
is supposed to do, as clearly stated in the documentation. 正如文档中明确指出的那样,这就是std::map::operator[]
应该做的。
If you don't want this (mostly useful) behaviour, use the find
member function instead of []
. 如果您不希望这种行为(最有用),请使用find
成员函数代替[]
。
At any rate, your code would fail even if []
didn't create a new element (or if you used find
) since you simply don't handle the case where segVar
isn't found in varSeg
. 无论如何,即使[]
没有创建新元素(或者您使用find
),您的代码也会失败,因为您根本无法处理在segVar
中找不到varSeg
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.