I want a map like this:
map< string, vector<CMyClass> > m_mymap;
Does anyone have any examples of inserting into a map like this, finding particular keys, getting the vector and adding to the existing vector, etc?
I want a map like this:
map< string, vector<CMyClass> > m_mymap;
Does anyone have any examples of inserting into a map like this, finding particular keys, getting the vector and adding to the existing vector, etc?
Using this map would not be different from many other maps. The insert function still works with make_pair(). Unless you know the key to a vector, you would use find(), and then dereference the resulting iterator to get to the vector, which can then be further accessed. Or is this your first time with maps?
first time with maps. I have been reading up but I was under the impression if I called find for a specific string key, I would just get a copy of the vector in the map. Therefore any push_back operation on the vector would not affect the vector in the map container. So this isn't the case?
Last edited by Jonnster; 11-16-2010 at 04:50 AM.
Yes, it is not the case.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I was expecting to do a find on the map, and with the iterator of this do:
(*i)->push_back(data);
This doesn't compile. So how would I push a new element to the vector?
Post the smallest and simplest program that demonstrates the compile error, and also post the compile error.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I've removed the checks on the find for simplicity.Code:map < string, vector <CMyClass> >::iterator i = m_MyMap.find("sometext"); CMyClass data; // code to set data removed (*i)->push_back(data);
The compiler error is
Code:error C2819: type 'std::pair<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const ,class std::vector<class CMyClass::CMyClass,class std::a llocator<class CMyClass::CMyClass> > >' does not have an overloaded member 'operator ->' error C2227: left of '->push_back' must point to class/struct/union
Last edited by Jonnster; 11-16-2010 at 05:43 AM.
Ah. It should actually be:
Code:i->second.push_back(data);
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It compiles now. Many thanks for your help.
What happens if find() doesn't find the key? Do you insert a new entry into the map and continue, or do you do something else.
I ask because often it's better to assume the key is in there or add it automatically if it's not by using the operator[] syntax:Code:m_MyMap["sometext"].push_back(data);