Reputation: 277
I want to use vector of Map in c++. I have list of mapped values, which I want to store as map in vector. My requirement goes something like this: 1. For N columns, I have a map of values . 2. I want to maintain map of for each i in N.
I am trying to maintain this in Vector >. Please let me know how to make it work.
I am using following code to add mappings
void fun()
{
vector< map < string, int> > myVect;
myVect.push_back(new map< string, int> );
myVect.push_back(new map< string, int> );
map< string, int> entry1 = myVect[0];
entry1["ABC"] = 1;
entry1["DEF"] = 2;
map< string, int> entry2 = myVect[1];
entry1["ABC"] = 5;
entry1["RKD"] = 9;
}
Why doesn't work ?
Upvotes: 6
Views: 22459
Reputation: 28178
Justin answered the big part of it but another issue is:
map< string, int> entry1 = myVect[0];
This will copy the map from your vector. You probably want a reference instead:
map< string, int>& entry1 = myVect[0];
Upvotes: 5
Reputation: 104698
In your example, you are pushing back using a pointer (via new
), and not by const reference or value. Your 'vector of maps' declaration is fine, but the insertion is causing a compiler error.
To push a map into the vector, use the form:
std::map<std::string,int> m;
// populate m if needed
x.push_back(m);
or simply
x.push_back(std::map<std::string,int>());
if you want to push an empty map.
Note that new
is not needed here.
Upvotes: 12