7

This piece of code seems work well, with default value for they value_type (int) as 0; does it work for all cases?

std::map<std::string,int> w;
for (const auto& t: str)
   w[t]++;

What about double? map? default 0.0?

wenfeng
  • 177
  • 1
  • 7

3 Answers3

9

Yes. When you use the []-operator on a map and no element with the desired key exists, a new element is inserted which is value-initialized. For an integer, this means initialized to zero.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
9

Yes, this code would work for any type of the key, including double. The reason this works is that the non-const operator [] returns a reference to the value at the key, not a copy of that value. It is that reference to which the ++ operator gets applied.

The code fragment that you show works as follows:

  • For each key t of type string in the str container,
  • The map w is searched for the given key
  • Since the entry is not there, a new one gets inserted into the map
  • Since the key of the entry is known, but the value is not, a default (value-initialized, e.i. 0 for int) object for the value gets created
  • A reference to the newly created object (in this case, int& initialized to zero) is returned to the caller
  • The ++ operator is applied to the reference returned from the [], which changes 0 to 1 (or 0.0 to 1.0, etc.)
Alexey
  • 9,197
  • 5
  • 64
  • 76
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I see. Thanks. This is actually my first question on stackoverflow. – wenfeng Apr 23 '13 at 21:50
  • @dasblinkenlight `a default object for the value gets created` , could you explain, why int is initialized to 0? AFAIC, default 'constructor' for `int` does not specify any particular value and the value expected to be undefined – Alexey May 02 '18 at 08:35
  • 2
    @Alexey It is important to distinguish between default initialization and value initialization for an `int`. If you write `int x;` then `x` is default-initialized, which for `int` means "no initialization is performed", because it's a POD type. If you write `int x = int()`, which is what containers do (except it's `T x = T()` for containers, because they are templates) then `x` is initialized to integer zero. – Sergey Kalinichenko May 02 '18 at 10:24
3

does it work for all cases?

For all cases, a new key will be associated with a value initialized to T().

When T is a built-in or Plain Old Data type, such as int or double, that evaluates to zero.

When T is a class, the map will attempt to call the empty constructor.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180