c++ push_back() inside a map of vectors

11,670
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).

Share:
11,670
Admin
Author by

Admin

Updated on June 08, 2022

Comments

  • Admin
    Admin almost 2 years

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