3

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)’
llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • Which C++ Standard? C++11? – Daniel Langr Dec 05 '18 at 12:31
  • Yup, but if the solution is different for other standards I'd appreciate for completness if you could also provide the differences, thanks –  Dec 05 '18 at 12:32
  • 1
    Possible duplicate of [emplace\_back not working with std::vector>](https://stackoverflow.com/questions/33207232/emplace-back-not-working-with-stdvectorstdmapint-int) – Daniel Langr Dec 05 '18 at 12:36

3 Answers3

4

You can list initialization:

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

vec.push_back(
        { {'d', 88}, {'e', 99} }
        );
llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • Could you elaborate a bit? I don't want to initialize the vector with some edges, I just want inside a loop to be able to push an edge to the vector without having to declare an edge, just passing the two values. –  Dec 05 '18 at 12:34
  • 1
    @SembeiNorimaki `push_back` is the same – llllllllll Dec 05 '18 at 12:35
  • 5
    @SembeiNorimaki you cannot push an edge to the vector because you don't have a vector of edge. You can push a map with one edge. – bolov Dec 05 '18 at 12:40
  • @SembeiNorimaki `std::map` has a constructor with a parameter of type `std::initializer_list`. Since `std::vector::push_back` has a parameter of `std::map` type here, that constructor is used (that's the reason why `emplace_back` does not work). – Daniel Langr Dec 05 '18 at 12:40
3

Use an extended initializer list, like this:

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

Live demo

Requires C++11, or later.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

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.

O Dundar
  • 90
  • 1
  • 6