Sorry if the question is very trivial.
I have a vector of maps:
typedef map<char, int> edges;
typedef vector<edges> nodes;
nodes n;
Now let's say I want to push a toy edge. I tried different things and what I worked is
edges e; //declare an edge
e['c'] = 1; //initialize it
n.push_back(e); //push it to the vector
How can I just push the pair of values of an edge ('c' and 2) without having to declare a variable and initialize it?
Something like:
n.push_back(edges('c',2));
but compiler gives an error
error: no matching function for call to ‘std::map<char, int>::map(char, int)’
Use an extended initializer list, like this:
Live demo
Requires C++11, or later.
In your solution, you add
map
to vector instead of pairs. A method should iterate over each element to place it in vector. Therefore you can access to element withn[0]['c']
etc.I thought, using
for_each
and a lambda expression with passing vector reference to create a one line solution to add pairs into vector.I hope this explains a solution for you.
You can list initialization: