Open In App

2D Vector in C++

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A 2D vector is a vector of the vectors i.e. each element is a vector in itself. It can be visualised as a matrix where each inner vector represents a row, and the number of rows represents the maximum columns. A 2D vector is dynamically resizable in both dimensions.

Syntax

C++
vector<vector<data_type>> V;

where data_type is the type of elements and V is the name assigned to the 2D vector.

Creating a 2D Vector

In C++, we can create/declare a 2D Vector by using the vector container defined in the C++ Standard Template Library(STL). We can simply create a 2D vector by creating a vector with the vector data type.

Just like vectors, a 2D vector can be created and initialized in multiple ways:

1. Default

An empty 2D vector can be created using the declaration below. It can be filled in later on in the program.

C++
vector<vector<data_type>> v;


2. With User Defined Size and Default Value

A vector of a specific size can also be declared and initialized to the given value as default value.

C++
vector<vector<T>> v(n, vector<T>(m, value));

where n is the number of rows, m is the number of columns, val is the new default value for all of the elements of the vector.

3. Using Initializer List

Vector can also be initialized using a list of values enclosed in {} braces separated by comma. The list must be nested according to the two dimensions as it helps in determining the row size and column size.

C++
vector<vector<T>> v = {{x1, x2 ...}, {y1, y2, ... }, ...};


Example:
Let’s take a look at an example that shows implements the above methods:

C++
#include <bits/stdc++.h>
using namespace std;

void printV(vector<vector<int>>& v) {
  	for (auto i: v) {
        for (auto j: i) {
            cout << j << " ";
        }
        cout << endl;
    }
  	cout << endl;
}

int main() {
  
  	// An empty 2D vector
  	vector<vector<int>> v1;
  
  	// 2D vector with initial size and value
  	vector<vector<int>> v2(2, vector<int>(3, 11));
  
    // A 2D vector initialized with initializer list
    vector<vector<int>> v3 = {
        {1, 2, 3},
        {4, 5, 6},
    };
	
  	printV(v1);
  	printV(v2);
  	printV(v3);
    return 0;
}

Output
11 11 11 
11 11 11 

1 2 3 
4 5 6 

To know more about initialization of 2D vector, please refer to the article - Initialize 2D Vector

Basic Operations on 2D Vector

The following are the basic operations of 2D vector:

  1. Inserting Elements in a 2D Vector
  2. Accessing and Updating Elements
  3. Deleting Elements
  4. Traversing the Vector

Inserting Elements in a 2D Vector

In 2d vectors, there are two types of insertion:

  • Inserting a new row.
  • Insert a value in an existing row.

These can be inserted at any given position using vector insert() and at the end using vector push_back(). As vector can dynamically grow, each row can have different size like Java's jagged arrays.

Let's take a look at an example of this operation:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<vector<int>> v = {{1, 2, 3},
                             {4, 5, 6}};
    
    // Insert a new row at the end
    v.push_back({7, 8, 9});
    
    // Insert value in 2nd row at 2nd position
    v[1].insert(v[1].begin() + 1, 10);
    
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size(); j++) {
            cout << v[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Output
1 2 3 
4 10 5 6 
7 8 9 

More methods of insertion are discussed here - Insert Elements into 2D Vector

Accessing and Updating Elements

As 2D vectors are organized as matrices with row and column, we need two indexes to access an element: one for the row number (i) and other for the column number (j). We can then use any access method such as [] operator or vector at() method.

The value of the accessed element can be changed by assigning a new value using = operator.

The below examples illustrate this operation:

C++
#include <bits/stdc++.h>
using namespace std;


int main() {
    vector<vector<int>> v = {{1, 2, 3},
        {4, 5, 6}};
    
	// Access 3rd element in 2nd row
  	cout << "3rd element in 2nd row: "<< v[1][2] << endl;
  
  	// Access 2nd element in 1st row
  	cout << "2nd element in 1st row: "<<v[0][1]<<endl;
  	
    //Updating the 2nd element in 1st row
  	v[0][1] = 9; 
  	cout << "2nd element in 1st row after updating: " <<v[0][1]<<endl;
  	
  	

    return 0;
}

Output
3rd element in 2nd row: 6
2nd element in 1st row: 2
2nd element in 1st row after updating: 9

Deleting Elements from a 2D Vector

Similar to insertion, there are two types of deletion in 2D vector:

  • Deleting a row.
  • Deleting a value in an existing row.

Elements can be deleted using vector erase() for a specific position or range and using vector pop_back() to remove the last element. Let’s take a look at an example of this operation:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<vector<int>> v = {{1, 2, 3},
                            {4, 5, 6}};
    
    // Delete the second row
    v.erase(v.begin() + 1);
    
    // Delete second element in first row
    v[0].erase(v[0].begin() + 1);

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

    return 0;
}

Output
1 3 

Traversing 2D Vector

Traversing a 2D vector involves iterating through rows and columns using nested loops and access the elements by indexes. Let’s take a look at an example of this operation:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<vector<int>> v = {{1, 2, 3},
                            {4, 5, 6}};
  
  	// Loop through rows
    for (int i = 0; i < v.size(); i++) {
      
      	// Loop through columns
        for (int j = 0; j < v[i].size(); j++)
            cout << v[i][j] << " ";
        cout << endl;
    }

    return 0;
}

Output
1 2 3 
4 5 6 

C++ provides more methods to traverse 2D vector which are discussed in this article - Iterate 2D Vector

Finding Size of 2D Vector

Finding the size of a 2D Vector involves finding its row size and column size which can be done using the vector.size() method. The size vector used on the outer vector gives there number of rows in the 2D vector while using them on the inner vector gives the number of columns in that row ( As all rows can have different number of columns).

Syntax

C++
//finding the number of rows
int rows = vec.size();

//finding the number of columns
int rows = vec[0].size();

where, vec is the name of the vector for which the size is to be determined. Since each element of a 2D vector is a vector itself we can use the size() method on the elements(vec[0]) to find the size of each row separately.

Example

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

int main() {
    // Creating a 2D vector
    vector<vector<int>> vec = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // Finding the number of rows 
    //(size of the outer vector)
    int rows = vec.size();
    cout << "Number of rows: " << rows << endl;

    // Finding the number of columns 
    //(size of any inner vector first row)
    int cols = vec[0].size();
    cout << "Number of columns: " << cols << endl;

    return 0;
}

Output
Number of rows: 3
Number of columns: 3

Common Operations and Applications

Apart from the basic operations, there are many operations that can be performed on 2D vectors:


Next Article
Article Tags :
Practice Tags :

Similar Reads