简体   繁体   English

c ++ push_back()在向量映射中

[英]c++ push_back() inside a map of vectors

I'm trying to dynamically add elements to a vector that is contained within a map, to store multiple arrays of "Particle" objects that are mapped to different ids. 我正在尝试动态地将元素添加到地图中包含的向量中,以存储映射到不同ID的多个“粒子”对象数组。 I'm new to the language and so I'm having trouble understanding if this can only be done with iterators? 我是语言的新手,所以我很难理解这是否只能用迭代器来完成? In this case it feels like overkill. 在这种情况下,感觉有点矫枉过正。 Is it possible to directly access a vector inside a map? 是否可以直接访问地图中的矢量? Since I can access the map elements by key, and because there is only one vector per key, it seems like it should be possible. 因为我可以按键访问地图元素,并且因为每个键只有一个向量,所以看起来它应该是可能的。 I don't really have exact code as an example but it would look something like this: 我没有确切的代码作为示例,但它看起来像这样:

int currentId = 1;  
map <int, vector<Particle> > particleMap;    
Particle p;  
particleMap[currentId] <access to vector somehow here?> push_back(p);

I'm sure I'm missing some larger concept here, but I find myself needing this type of data structure a lot, so it would be great to know the proper way to access these kinds of "tables." 我确信我在这里缺少一些更大的概念,但我发现自己需要这种类型的数据结构,所以知道访问这些“表”的正确方法会很棒。

particleMap[currentId].push_back(p);

will work just fine. 会工作得很好。

There is only one vector per id; 每个id只有一个vector ; this is what you are referring to with particleMap[currentId] . 这就是你用particleMap[currentId]指的。 Then you just continue with the expression as if you were writing myVector.push_back(p) . 然后你就像继续编写myVector.push_back(p)一样继续表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM