I'm making a 2D vector for a memory match game, the user input defines the size with variables rows and columns. The following code is only how the 2D vector is populated, there is a separate function that prints the vector.
std::cout << "Creating a 2-dimensional vector, enter row size: ";
int row_size;
std::cin >> row_size;
std::cout << "Enter column size: ";
int col_size;
std::cin >> col_size;
// create a 2 dimensional int vector with known dimensions
std::vector<std::vector<int>> aVector(row_size, std::vector<int>(col_size));
Normally when passing an array as a function parameter the size of the array must also be passed. With std::vector there is no need, the vector keeps track of its size.
I use a templated function so I can use one function for different type vectors. Passing a 2D vector is easy:
This function will print 2D vectors of a single POD type. int, double, float, char, etc.
The advantages of dealing with a true 2D vector outweighs IMO the not-as-easy way of constructing one compared to a 2D array. Especially useful is being able to create a 2D vector at runtime without having to muck around with manually allocating memory.
I was curious if a 2D vector would work with range-based for loops. Your range-based for loop to fill the 2D vector made me rethink my output function: