简体   繁体   English

如果在std :: map中操作不存在的键/值对,会发生什么?

[英]What happens if one manipulates non-exist key-value pair in a std::map?

Say we have a std::map, declared as: 假设我们有一个std :: map,声明为:

std::map<int, int> m;

Then, we immediately do this: 然后,我们立即执行以下操作:

m[0]++;

What happens? 怎么了? According to my little experiment, m[0] goes to '1', as if there had been a '0' stored for key '0'. 根据我的小实验,m [0]变为“ 1”,就好像为键“ 0”存储了“ 0”一样。

But what if the map contains, say, custom types? 但是,如果地图包含自定义类型,该怎么办?

std::map<E, T> m;
m[e].function();

Would this work? 这行得通吗?

Actually I was wondering how C++ standard specifies this:) 实际上,我想知道C ++标准如何指定这一点:)

the overloaded operator[] for std::map actually creates the element passed as the argument, so by doing m[0]++ you insert an int and do ++ on it. std::map的重载operator[]实际上会创建作为参数传递的元素,因此,通过执行m[0]++您可以插入一个int并对其进行++处理。 Nothing wrong with it being 1 它是1没错

A call to this function is equivalent to: 对该函数的调用等效于:
(*((this->insert(make_pair(k,mapped_type()))).first)).second

The std::map will introduce an "empty" element when you use the operator[] to access an entry. 当您使用operator[]访问条目时, std::map将引入一个“空”元素。

If you don't want there to be an empty element, then you need to use std::map::find() to check if the element is there, and if it's not, don't use it. 如果您不希望有一个空元素,则需要使用std::map::find()检查该元素是否存在,否则请不要使用它。

Of course, as long as your type T is fine to have function() called on it, nothing bad will happen from m[e].function() . 当然,只要您的T类型可以function()m[e].function()就不会发生任何问题。 If T needs to be initialized with something useful before function() can be called, you'll have to make sure this doesn't happen. 如果在function()之前需要使用一些有用的东西来初始化T ,则必须确保不会发生这种情况。

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

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