Barry Tormey
Barry Tormey

Reputation: 3126

Two Dimensional Vector push_back

I have a two dimensional vector A made up of other vectors B

vector < vector < int >> A

vector < int > B

I use the push_back function to populate B.

B.push_back(1);
B.push_back(2);
B.push_back(3);

After that vector is populated, I use push_back again to populate A with B

A.push_back(B)

This is done several times so that A eventually results in a vector containing several other vectors looking like:

A { {1 , 2 , 3 }, { 2, 2, 2 }, {8, 9, 10} }

How can I make a call to a specific index in A and then continue to add to the vector so that the output would be similar to

A { {1 , 2 , 3 }, { 2, 2, 2, 4, 5, 6 }, {8, 9, 10} }

Something along the lines of

A[2].push_back(4);
A[2].push_back(5);
A[2].push_back(6);

Upvotes: 14

Views: 37006

Answers (2)

iambeanie
iambeanie

Reputation: 315

A[2].push_back(4);
A[2].push_back(5);
A[2].push_back(6);

Should work perfectly fine. Except if you want the second element then you'll need to use a[1] as vectors are 0 based.

Upvotes: 2

Jesse Good
Jesse Good

Reputation: 52365

What you have is correct except that indexes start at 0, so it should be A[1].push_back(4); and not 2.

Upvotes: 13

Related Questions