initialize std::map value when its key does not exist

房东的猫 提交于 2019-12-01 23:41:08

may I know where I can find a reference for this claim?

This is what the C++11 Standard mandates. Per paragraph 23.4.4.3:

T& operator[](const key_type& x);

1 Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

[...]

T& operator[](key_type&& x);

5 Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.

Concerning the second question:

Is there any way to invoke the one-argument constructor of map's Value(s) ?

You could do this in C++03:

void some_other_add(int j, int k) {
    myMap.insert(std::make_pair(j, Value(k)));
}

And use the emplace() member function in C++11:

myMap.emplace(j, k);

You'll find a helpful description of std::map<…>::operator[] at cppreference.com.

I assume you want to conditionally add a Value using a non-default constructor, i.e., when the corresponding key isn't present in the map.

C++03

std::map<int, Value>::iterator i = myMap.find(j);
if (i == myMap.end())
    i = myMap.insert(std::map<int, Value>::value_type(j, 123)).first;
i->add(k);

C++11

auto i = myMap.find(j);
if (i == myMap.end())
    i = myMap.emplace(j, 123).first;
i->add(k);

In both cases, newly inserted Values will have some_member == 123.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!