Is the value of primitive types in std::map initia

2019-06-15 14:00发布

Consider the following code:

map<int,int> m;
for(int i=0;i<10000;++i) m[i]++;
for(int i=0;i<10000;++i) printf("%d",m[i]);

I thought the the values printed out would be undefined because primitive types doesn't have default constructor, but here I got 10000 1s every time I tested.

Why is it initialized?

4条回答
乱世女痞
2楼-- · 2019-06-15 14:39

When invoking operator[] and the key is missing, the value is initialized using the expression mapped_type() which is the default constructor for class types, and zero initialization for integral types.

查看更多
Deceive 欺骗
3楼-- · 2019-06-15 14:40

In the C++14 standard, section [map.access] the text is:

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.

So, as also stated by Joseph Garvin's answer, the result of the expression mapped_type() is what is inserted. This sort of initialization is called value-initialization.

The meaning of value-initialization is not quite as simple as offered in the other answers, for class types. It depends on what sort of constructors the class type has, and whether the class is an aggregate, as explained by the cppreference link.

For int as in this question, value-initialization means the int is set to 0.

查看更多
混吃等死
4楼-- · 2019-06-15 14:52

See https://www.sgi.com/tech/stl/stl_map.h

  _Tp& operator[](const key_type& __k) {
    iterator __i = lower_bound(__k);
    // __i->first is greater than or equivalent to __k.
    if (__i == end() || key_comp()(__k, (*__i).first))
      __i = insert(__i, value_type(__k, _Tp()));
    return (*__i).second;
  }

In your example, _Tp is int, and int() is 0

#include <iostream>
using namespace std;
int main() {
  int x = int();
  cout << x << endl;
  return 0;
}

In addition:

thanks to @MSalters who tells about code above is SGI instead of std::map, But I think it is some like...

查看更多
Evening l夕情丶
5楼-- · 2019-06-15 14:53

std::map::operator[] inserts new value if it's not exist. If an insertion is performed, mapped value is initialized by default-constructor for class-types or zero-initialized otherwise.

查看更多
登录 后发表回答