时间:2019-05-16 标签:c++unordered_map ofvectors

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11081308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:49:48  来源:igfitidea点击:

c++ unordered_map of vectors

c++stlvectorunordered-map

提问by user1463416

So conceptually I'm trying to create a hash of arrays of pointers to my object.

所以从概念上讲,我试图创建指向我的对象的指针数组的散列。

The hash key is an int for the type of the object, and the array is a list of the objects to render.

哈希键是对象类型的 int,数组是要呈现的对象列表。

What I'm trying to do is :

我想要做的是:

unordered_map<int, vector<Object*> > drawQueue;
drawQueue.clear(); // new empty draw queue

for ( ... ) {
   drawQueue.at(type).push_back(my_obj);
}

So I'm not familiar enough with the nuances of the STL stuff, since I get an exception saying out_of_bounds, which is what happens when the key doesn't exist.

所以我对 STL 内容的细微差别还不够熟悉,因为我收到一个异常,说 out_of_bounds,当密钥不存在时会发生这种情况。

So I figured I need to create the key first, and then add to the vector :

所以我想我需要先创建密钥,然后添加到向量中:

if (drawQueue.count(type)) {
    // key already exists
    drawQueue.at(type).push_back(my_obj);
} else {
    //key doesn't exist
    drawQueue.insert(type, vector<Object*>); // problem here
    drawQueue.at(type).push_back(my_obj);
}

But now I'm really lost, as I don't know how to create/initialise/whatever an empty vectorto the insert of the unordered_map...

但现在我真的迷路了,因为我不知道如何创建/初始化/任何空vector的插入unordered_map......

Or am I doing this the entirely wrong way?

还是我这样做完全错误?

Any hints wise peoples?

有智慧的人有什么提示吗?

回答by betabandido

You are not using insertin the proper way. This should work:

您没有insert以正确的方式使用。这应该有效:

drawQueue.insert(std::make_pair(type, std::vector<Object*>()));

If using C++11, the previous statement can be simplified to:

如果使用C++11,前面的语句可以简化为:

drawQueue.emplace(type, std::vector<Object*>());

By using this approach the element is constructed in-place (i.e., no copy or move operations are performed).

通过使用这种方法,元素就地构建(即,不执行复制或移动操作)。

I also include links to the documentation for insertand emplace.

我还包含了insert和文档的链接emplace

回答by Venkata Gogu

I think this is an easy approach. My example will create an unordered_map string as key and integer vector as values.

我认为这是一个简单的方法。我的示例将创建一个 unordered_map 字符串作为键和整数向量作为值。

unordered_map<string,vector<int>> keys;
keys["a"] = vector<int>(); // Initialize key with null vector
keys["a"].push_back(1); // push values into vector.
keys["a"].push_back(5);    
for(int i : keys["a"] ){
    cout << i << "\t";
}