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, 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.)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With