我在声明 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为空。运算符[]将把 key 插入到映射中,并将其值定义为该类型的默认值(在这种情况下,整数为零)。

所以子表达式:
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

07-28 03:45