2

I have been following a tutorial on how to output two-dimensional vector with C++ and arrived at the following code:

#include <iostream>
#include <vector>
using namespace std;

int main()
{

    vector < vector < int > > test { { 1, 2, 3,
                                       4, 5, 6,
                                       7, 8, 9  } };

    for( unsigned int i = 0; i < test.size(); i++ )
    {
        for( unsigned int j = 0; j < test[i].size(); j++ )
        {
            cout << test[i][j] << " ";
        }
        cout << endl;
    }
}

which produces the following output:

1 2 3 4 5 6 7 8 9

As you can see my results do not look exactly as intended; i want to be able to output the vector into a two-dimensional grid-like space. As far as I can tell my code follows the example, but the cout << endl; after the inner for loop is not breaking the vector into rows like it should be. Can someone please explain to me what I am doing wrong, or show me the proper method to output a two-dimensional vector into a grid-like pattern?

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47

1 Answers1

5

Your top vector test has only one entry, which is a vector of int {1,2,3,4,5,6,7,8,9}, so it's size is actually 1. Thus the outer for loop will iterate only once and you get a flat output.

In order to get what you expect, you need either to initialize your top vector with multiple entries -- Like what was commented: vector<vector<int>> test {{1, 2,3},{4,5,6}, {7, 8, 9}}; , or push more entries after initialization.

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47