c++ push_back() inside a map of vectors

拈花ヽ惹草 提交于 2020-01-01 05:36:09

问题


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. 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."


回答1:


particleMap[currentId].push_back(p);

will work just fine.

There is only one vector per id; this is what you are referring to with particleMap[currentId]. Then you just continue with the expression as if you were writing myVector.push_back(p).



来源:https://stackoverflow.com/questions/5293466/c-push-back-inside-a-map-of-vectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!