2D Vectors in cpp visually explained

2D Vectors in cpp visually explained

How do create a two dimensional vector ?? Let us find out today with this code nugget,

#include <iostream>
#include <vector>

#define rowCount 3
#define columnCount 4

int main()
{
  std::vector<int> singleRow(columnCount, 5); 
  std::vector<std::vector<int>> matrix(rowCount, singleRow); 

  for(auto i : matrix) 
    for(auto i : singleRow)
        std::cout<<i<<" ";
  return 0;
}

Taking baby steps, With reference to above program, a vector called singleRow is initialized with 4 elements each holding the value 5, so far so good,

std::vector<int> singleRow(columnCount, 5);

Digging deep into above line of code, this constructor from vector takes two parameters,

  • Parameter one takes the no of elements in vector
  • Parameter two takes the value to be initialized

Going by this description, this is the result of above piece of code

image.png

Now coming to next step,

Q :What is a 2D vector ?
A : It is a vector of vector

Not so helpful right ? Imagine a 2D vector as a table, how to store a table in memory ?
This is how we do it,

std::vector<std::vector<int>> matrix(rowCount, singleRow);

With the definition of vector initialization we learnt, dissect above piece of code,

  • Parameter one provides no of elements for the vector named matrix,
  • Parameter two provides, the value to initialize the vector with, in this case, you guessed it right, another vector named singleRow. Look closely at the type of matrix, it is a vector which holds a vector

    std::vector<std::vector<int>> matrix;
    

    End result will look like this, image.png

    And before we wind up, remember, in memory vector content will be stored sequentially just like a series of boxes, the table structure is just a visual model for us to relate.

You are not believin me ?? Observe the output this piece of code produces,

  for(auto i : matrix) 
    for(auto i : singleRow)
        std::cout<<i<<" ";

A beautiful, single file of integers, That's all for this nugget, have a great day ☕

Did you find this article valuable?

Support cppnuggets by becoming a sponsor. Any amount is appreciated!