Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ push_back() inside a map of vectors

Tags:

c++

map

vector

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

like image 395
Reese Avatar asked Mar 14 '11 00:03

Reese


1 Answers

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

like image 88
Jon Avatar answered Sep 21 '22 06:09

Jon