gpt4 book ai didi

c++ - 如何在 C++ 中设置大小并将映射初始化为零

转载 作者:太空狗 更新时间:2023-10-29 19:46:54 24 4
gpt4 key购买 nike

我正在声明一个 map ,例如 map<string,int> registers .如何将其设置为特定大小以及如何将其所有值设置为零,以便稍后可以在映射值中插入值?

最佳答案

这个怎么样:

std::map<std::string, int>   registers; // done.
// All keys will return a value of int() which is 0.


std::cout << registers["Plop"] << std::endl; // prints 0.

这是有效的,因为即使 registers 是空的。运算符 [] 会将键插入映射并将其值定义为类型的默认值(在本例中整数为零)。

所以子表达式:

registers["Plop"];

相当于:

if (registers.find("Plop") == registers.end())
{
registers.insert(make_pair("Plop", 0));
}
return registers.find("Plop").second; // return the value to be used in the expression.

这也意味着以下工作正常(即使您之前没有定义 key )。

registers["AnotherKey"]++; // Increment the value for "AnotherKey"
// If this value was not previously inserted it will
// first be inserted with the value 0. Then it will
// be incremented by the operator ++

std::cout << registers["AnotherKey"] << std::end; // prints 1

关于c++ - 如何在 C++ 中设置大小并将映射初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com