C++20 sections · 1024 units
Open in Course

2D Vectors

Creating grids

I'll show you how to create grids and matrices with nested vectors. You declare vector<vector> grid to make a vector of vectors. To initialize a 3x4 matrix of zeros, use vector<vector> grid(3, vector(4, 0)) which creates three rows with four columns each.

Access elements with grid[row][col] like grid[1][2] for row 1, column 2. Each inner vector can have different sizes, so you can make jagged arrays. To get row count use grid.size(), and for columns in row i use grid[i].size().

Never assume uniform column sizes unless you initialized them identically.