Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert std::map into std::vector directly

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 Answers

You can list initialization:

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

vec.push_back(
        { {'d', 88}, {'e', 99} }
        );
like image 179
llllllllll Avatar answered Mar 09 '26 01:03

llllllllll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!