0
0
CppHow-ToBeginner · 3 min read

How to Create 2D Vector in C++: Syntax and Example

In C++, you create a 2D vector using std::vector<std::vector<T>>, where T is the type of elements. You can initialize it with sizes and default values like std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));.
📐

Syntax

A 2D vector in C++ is a vector of vectors. The syntax is std::vector<std::vector<T>>, where T is the type of the elements (like int, double, etc.). You can specify the number of rows and columns and an initial value for each element.

  • rows: number of inner vectors (rows)
  • cols: number of elements in each inner vector (columns)
  • initial_value: value to fill each element with
cpp
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, initial_value));
💻

Example

This example creates a 3x4 2D vector of integers, initializes all elements to zero, then prints the matrix.

cpp
#include <iostream>
#include <vector>

int main() {
    int rows = 3;
    int cols = 4;
    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));

    // Print the matrix
    for (const auto& row : matrix) {
        for (int val : row) {
            std::cout << val << ' ';
        }
        std::cout << '\n';
    }

    return 0;
}
Output
0 0 0 0 0 0 0 0 0 0 0 0
⚠️

Common Pitfalls

One common mistake is to create a 2D vector without initializing inner vectors properly, which can cause runtime errors when accessing elements. Another is mixing up rows and columns sizes.

Wrong way: creating outer vector and then pushing inner vectors without setting their size can lead to out-of-range errors.

cpp
// Wrong way: inner vectors not sized
std::vector<std::vector<int>> matrix_wrong(3);
// Accessing matrix_wrong[0][0] here causes error because inner vector is empty

// Right way: initialize inner vectors with size
std::vector<std::vector<int>> matrix_right(3, std::vector<int>(4, 0));
📊

Quick Reference

  • Declare: std::vector<std::vector<T>> name(rows, std::vector<T>(cols, initial_value));
  • Access element: name[row][col]
  • Resize: Use resize() on outer and inner vectors
  • Iterate: Use nested loops or range-based for loops

Key Takeaways

Use std::vector> to create a 2D vector in C++.
Initialize inner vectors with a size to avoid out-of-range errors.
Access elements using matrix[row][col] syntax.
You can set default values for all elements during initialization.
Resize outer and inner vectors separately if needed.