kmlkz
kmlkz

Reputation: 63

initializing vector with pair

I'm having trouble initializing vectors with pairs; My code doesn't seem to work, result of adj_list[0][0].first doesn't show 1:

vector < vector <pair <int, int> > > adj_list;
adj_list.insert(adj_list.end(), { { (make_pair(1,20), make_pair(2,5)), (make_pair(1,7),make_pair(0,2)) }});

What i'm trying to do is to create an adjacency list (hardcoded), with this structure:

adj_list[0] ---- make_pair(1,20), make_pair(2,5)

adj_list[1] ---- make_pair(0,7),make_pair(3,9)

How do i go about doing this?

Upvotes: 1

Views: 489

Answers (2)

molbdnilo
molbdnilo

Reputation: 66371

You're using the wrong brackets, which makes (make_pair(1,20), make_pair(2,5)) use the comma operator and its value is make_pair(2,5).

You should use curly brackets:

adj_list.insert(adj_list.end(), { { {make_pair(1,20), make_pair(2,5)}, {make_pair(1,7),make_pair(0,2)} }});

But, on the other hand: that's not an initialisation.
The vector has already been initialised to the empty vector.

This is an initialisation (you also don't need make_pair):

vector<vector<pair<int, int>>> adj_list = {{{1, 20}, {2,5}},
                                           {{1, 7}, {0, 2}}};

Upvotes: 4

Marco A.
Marco A.

Reputation: 43662

You're calling the comma operator, the correct syntax to insert (not initialize) would be

adj_list.insert(adj_list.end(), { 
                                 { make_pair(1,20), make_pair(2,5) }, 
                                 { make_pair(1,7),  make_pair(0,2) } 
                                });

Upvotes: 2

Related Questions