简体   繁体   中英

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. 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; 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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