Philip Hamoui Philip Hamoui - 5 months ago 28
C++ Question

Print the contents of a 2D vector using auto

I have the vector of vectors

a
, and I want to print out the contents of the first vector.

a = [ 1 5 3 ; 11 17 14 ]


knowing it's size/dimension, I could do that using the following:

for ( int k = 0; k <= a[0].size(); k++)
cout << a[0][k] << endl;


and the output, as I wanted it, is:

1 5 3


However, in another example where the vector changes its size during execution, I tried to use the following:

for ( auto k : a[0])
cout << a[0][k] << endl;


but the output is as the following:

5 0


How can I get the elements of the first vector using the
auto
keyword without knowing the dimensions of the vector?

Answer Source

When you use the auto keyword, k is being assigned to the value of each element in the vector, not the index of the element. Therefore, if you wanted to print out the contents of the array, print out just k:

for ( auto k : a[0] )
    cout << k << endl;

EDIT: For clarity, the reason it works in the first for loop is because you are setting k to be every integer from 0 to the number of elements in a[0], and therefore the index of each element, rather than the value.