这段代码似乎运行良好,它们value_type( int) 的默认值为 0;它适用于所有情况吗?
std::map<std::string,int> w;
for (const auto& t: str)
w[t]++;
双倍呢?地图?默认0.0?
这段代码似乎运行良好,它们value_type( int) 的默认值为 0;它适用于所有情况吗?
std::map<std::string,int> w;
for (const auto& t: str)
w[t]++;
双倍呢?地图?默认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.
是的,此代码适用于任何类型的密钥,包括double. 这样做的原因是非常量operator []返回对键值的引用,而不是该值的副本。它是++应用运算符的引用。
您显示的代码片段的工作原理如下:
t类型string的键,strw上搜索给定的键0for int)对象int&初始化为零)返回给调用者++运算符应用于从 中返回的引用,该引用更改[]为0(1或更改0.0为1.0等)