store objects in vector, which is inside a map in C++ -



store objects in vector, which is inside a map in C++ -

i trying create map contains string key , vector of myclass.

std::map<string,vector<myclass>> m;

i need populate vector , map dynamically (reading values file).

class myclass{ string datamember1; ... myclass() { ... } };

how should proceed it??

also want able access objects in vector based on string key.

for example:

std::map<string,vconnect>::iterator pos; pos = mapgraph.find(string); cout<<(pos->second)[0]->datamemberofmyclass

will (pos->second)[0] indicate first myclass object stored in vector??

thanks

generally, when mapped type container, using [] everywhere works well; if entry isn't present, created empty container, things like:

m[key].push_back( newelement );

or

m[key].begin(), m[key].end()

or even:

if ( !m[key].empty() ) dosomethingwith( m[key].second[0] );

work correctly. if you're doing number of operations on same element (as in lastly 2 cases), might want hold in reference:

std::vector<myclass>& elem = m[key]; // ...

about exception if you're not modifying element, , don't want create entry if empty. in cases, you'll need find, , test:

std::map<std::string, std::vector<myclass>>::const_iterator entry = m.find( key ); if ( entry != m.end() ) { std::vector<myclass>& elem = entry->second; // ... }

c++ vector maps

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -