简体   繁体   中英

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.

I'm currently having 2 maps

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.

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. A new entry was created inside varSeg map with key segVar and a value of Null for the Segment. 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? 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.

If you don't want this (mostly useful) behaviour, use the find member function instead of [] .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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