Insert std::map into std::vector directly

2019-05-14 15:32发布

问题:

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)’

回答1:

You can list initialization:

nodes vec {
    { {'a', 12}, {'b', 32} },
    { {'c', 77} },
};

vec.push_back(
        { {'d', 88}, {'e', 99} }
        );


回答2:

Use an extended initializer list, like this:

n.push_back({ {'c', 2} });

Live demo

Requires C++11, or later.



回答3:

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 with n[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.

#include <algorithm> 

typedef map<char, int> edges;
//change this to take pair
typedef vector<pair<char, int>> nodes;

nodes n;
edges e;        //declare an edge

//map elements are pairs
for_each(e.begin(), e.end(), [&n](pair<char, int> p) { n.push_back(p); });

I hope this explains a solution for you.