开发者

Creating a vector of specific size in a map C++

Hi suppose I want to create a map of the form map<int, vector<node> > where node is defined as

struct node{
    string key;
    double pnum;
    node():key(""),pnum(0) {}
};

Now If someone gives me a map key, say "Element_1" and a vector size 2 is it alright/safe to create the vector under the key "Element_1" as it has been done below?

int main(void)
{
    map<string,vector<node> > samplemap;    
    samplemap["Element_1"] = vector<node>(2);
}

The above code compiles and I am able to print out the vector stored under the key "Element_1". (Default values p开发者_如何转开发rinted).


If someone gives me a map key, say "Element_1" and a vector size 2 is it alright/safe to create the vector under the key "Element_1" as it has been done below?

Yes, my friend. If the key already exists, then it updates the associated value, otherwise it creates a new entry with the key with default value [i.e vector<node>()] which then gets updated the specified value [i.e vector<node>(2)].

By the way, vector<node>(2) creates a vector of size 2. That means, it will have two elements of type node created by calling the default constructor of node.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜