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?
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?
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.
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:
t
of type string
in the str
container,w
is searched for the given key0
for int
) object for the value gets createdint&
initialized to zero) is returned to the caller++
operator is applied to the reference returned from the []
, which changes 0
to 1
(or 0.0
to 1.0
, etc.)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.