Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Dimensional Vector push_back

Tags:

c++

vector

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);
like image 944
Barry Tormey Avatar asked May 01 '13 04:05

Barry Tormey


People also ask

Can we use Push_back in 2D vector?

Insertion in Vector of VectorsElements can be inserted into a vector using the push_back() function of C++ STL. Below example demonstrates the insertion operation in a vector of vectors. The code creates a 2D vector by using the push_back() function and then displays the matrix.

What is a 2 dimensional vector?

Two-Dimensional Vectors The magnitude of a vector is the total amount of the quantity represented by the vector. For a two-dimensional vector, the magnitude is equal to the length of the hypotenuse of a triangle in which the sides are the x- and y-components.

What does Push_back mean?

The push_back() function is used to insert an element at the end of a vector. This function is available in the <vector> header file.


2 Answers

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

like image 174
Jesse Good Avatar answered Oct 09 '22 12:10

Jesse Good


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.

like image 38
iambeanie Avatar answered Oct 09 '22 11:10

iambeanie