[英]C++ map insertion using []
I see that the code in subscript operator is like this for a std::map
when the key is not found. 我发现未找到密钥时,下标运算符中的代码对于std::map
来说像这样。 But here they add a default value. 但是在这里,它们添加了默认值。
__i = insert(__i, value_type(__k, mapped_type()));
Now if I do 现在如果我这样做
std::map<std::string,int> mapped;
mapped["current"] = 5;
I wanted to know how is this pair added to the map using the above statement. 我想知道如何使用上面的语句将这对添加到地图上。
operator[]
inserts the element of the map if it was not found, and then returns it. 如果找不到地图, operator[]
插入地图的元素,然后将其返回。
Therefore, the parameters key (__i) and value (__k) are added to the map. 因此,参数键(__i)和值(__k)被添加到映射中。
This is one STL implementation: 这是一个STL实现:
_Tp& operator[](const key_type& k) { // k is the parameter you passed
iterator i = lower_bound(k);
// if i -> first >= k then insert a place for the new element.
if (i == end() || key_comp()(k, (*i).first))
i = insert(i, value_type(k, _Tp()));
// return a reference to the element mapped to by the key
return i -> second;
}
Since a reference is returned, this acts the exact same way as accessing an array does: 由于返回了引用,因此其行为与访问数组的行为完全相同:
You can assign ray[5] = 10
and access int i = ray[5]
. 您可以分配 ray[5] = 10
并访问 int i = ray[5]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.