如何在c ++中设置大小并将地图初始化为零

Sha*_*adi 3 c++ maps

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

Mar*_*ork 10

这个怎么样:

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.
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为即使registers是空的.operator []会将键插入到映射中,并将其值定义为类型的默认值(在这种情况下,整数为零).

所以子表达式:

registers["Plop"];
Run Code Online (Sandbox Code Playgroud)

相当于:

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.
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)


Chr*_* A. 5

我如何将其设置为特定大小以及如何将其所有值设置为零

这可能更多是一个概念问题,而不是语法/“如何”问题。是的,确实如此,正如许多发帖者/评论者所说,只需使用给定的密钥进行初始访问,就会创建相应的值并默认设置为 0。但您使用的一个不合适的重要短语是:

它的所有价值

它一开始就没有值,如果您在编程时假设它有值,那么仅此一点就可能导致概念错误。

通常最好养成查找密钥是否在映射中的习惯,如果不在,则执行某些操作来初始化它。尽管这看起来只是开销,但像这样显式地执行操作可能会防止将来发生概念错误,特别是当您尝试访问键的值而不知道它是否已经在映射中时。

一行摘要:您不想自己初始化该值,而不是让映射为任何给定键的值分配其默认值吗?

因此,您可能想要使用的代码是:

    if(mymap.find(someKey) == mymap.end())
    {
        // initialize it explicitly
        mymap[someKey] = someInitialValue;
    }
    else
    {
        // it has a value, now you can use it, increment it, whatever
        mymap[someKey] += someIncrement;
    }
Run Code Online (Sandbox Code Playgroud)