What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

2D Vectors in C++: Declaration, Operations & Traversal

  • Dec 08, 2022
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
2D Vectors in C++: Declaration, Operations & Traversal

We all are familiar with arrays in C++, but today in this article we are going to look at the array but with dynamic properties like 2D Vector. Yes! you already know what we are talking about. So, vectors are nothing but arrays with dynamic properties, and let's quickly dive into them. 

What is a Vector?

Vectors are dynamic arrays, whenever an element is inserted or deleted they can resize themselves automatically. Elements are stored at contiguous storage therefore iterators can be used to access and traverse.

Given below is the syntax to declare a 1D vector in C++ :

Syntax

vector<datatype> variable_name;

 

Basic Operations in Vectors?

Let us check different operations on vectors that can be performed which are provided by the class vector.

Some basic operations are :

Operation Description
push_back() function It adds a single element at the end of the vector.
pop_back() It removes a single element from the end of the vector.
at() It is used to access the elements using indexes.
size() It is used to return a total number of elements present in the vector.
empty() It is used to check whether the vector is empty or not.

 

Example: 

// Welcome to favtutor
#include<iostream> 
#include<vector>  // provided by STL
using namespace std;

int main()
{

    // Method1 : Initializer List
    vector<int> v1 = {10, 20, 30, 40, 50};

    // Method 2 : Uniform Initialization
    vector<int> v2{60, 70, 80, 90, 100};

    // Method 3
    vector<int> v3(5, 7); // five times 7

    cout << "vector1 : ";

    // for loop
    for (int i = 0; i < 5; i++)
    {
        cout << v1[i] << "  ";
    }

    cout << "\nvector2 : ";

    // ranged loop
    for (const int &i : v2)
    {
        cout << i << "  ";
    }

    cout << "\nvector3 : ";

    // ranged loop
    for (int i : v3)
    {
        cout << i << "  ";
    }

    return 0;
}

 

Output:

vector1 : 10  20  30  40  50  
vector2 : 60  70  80  90  100  
vector3 : 7  7  7  7  7

 

What is a 2D vector?

Vector of Vectors is a 2D vector, it is nothing but a dynamic array in C++ means it has the ability to resize itself automatically, whenever we add or remove elements in it. Like a 2D array, it consists of rows and columns where each row is a different type of vector. 

In order to use vectors in our program, we must include the vector header file provided by the Standard Template Library :

#include<vector>

Also, to include all kinds of Standard Template Libraries (STL) at once, we can use :

#include<bits/stdc++.h>

 

How to declare a 2D vector in C++?

Given below is the syntax to declare a 2D vector in C++ :

Syntax : 

vector<vector> vec;

 

How to Initialize a 2D vector in C++?

There are various ways to initialize a 2D vector in C++.

Method 01) Using the above syntax.

/* Welcome to favTutor */
#include<vector> 
using namespace std;
int main()
{
    // Normal 2D vector initialization
    vector<vector<int>> vect;

    return 0;
}

 

Method 02) Initializing a 2D vector with vectors as elements inside it.

// Welcome to favTutor
// 2D vector with elements(vectors) inside it.

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

int main()
{
    // Initializing a 2D vector with vectors as elements inside it.
    vector<vector<int>> v{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}};

    // prinitng the above 2D vector
    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;
}

 

Method 03) Initializing a 2D vector where each row has values associated with them as defined by the user.

/*
Welcome to favTutor
A 2D vector where each row has values associated
with them as defined by the user.
*/

#include<vector>
#include<iostream>
using namespace std;
int main()
{

    /* Number of rows our vector will have */
    int row = 5;

    /* values associated with each vector elements */
    int column[] = {5, 3, 4, 2, 1};

    /*
    creating a 2D vector with size 'row' units.
    */

    vector<vector<int>> vec(row);

    /*
    Assigning the values of rows and
    columns through a nested for loop,
    in our 2D vector.
    */

    for (int i = 0; i < row; i++)
    {
        /* Declaring the size of the column. */
        int col = column[i];

        /*
        We have the i-th row to the size of the column.
        We create a normal vector of capacity "col" which
        in every iteration of the for loop will define the
        values inside of each row.
        */
        vec[i] = vector<int>(col);
        for (int j = 0; j < col; j++)
        {
            vec[i][j] = 2;
        }
    }

    /*
    Printing the 2D vector that we just created above.
    */

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

 

Method 04) Initializing a 2D vector of size 'n' rows and 'm' columns with all element values as 1.

// Welcome to favTutor
#include<vector> 
#include<iostream>
using namespace std;
int main()
{
    int n = 5;
    int m = 3;

    /*
    We create a 2D vector having "n"
    rows each having the value "vector (m, 1)".
    "vector (m, 1)" declares a vector having "m"
    elements each of value "1".
    */
    vector<vector<int>> vec(n, vector<int>(m, 1));

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << vec[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

 

Some Operations On 2D Vectors

Insertion: Using push_back() function 

Example 1:

Suppose we have a vector of vectors v1 and I want to push vector v2 = {4,5,6} inside it. Then,

v1.push_back(v2);

(This will push the v2 vector into the vector of vectors v1).

Now v1 becomes : v1 = {{4,5,6}}.

Example 2:     

Now, I want to push vector v3 in the above-created vector of vector v1. Then, (v3 = {1,2,3})

v1.push_back(v3); 

This will result in :

v1 = {{4,5,6},{1,2,3}}

Below is the C++ program to demonstrate the above :

// Welcome to favTutor
// C++ program for inserting a vector
// into a vector of vectors

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

// Defining the rows and columns of
// vector of vectors
#define ROW 4
#define COL 5

int main()
{
    // Initialization
    vector<vector<int>> vec;
    int num = 1;

    // Inserting elements into vector
    for (int i = 0; i < ROW; i++)
    {
        // Vector to store column elements
        vector<int> v1;

        for (int j = 0; j < COL; j++)
        {
            v1.push_back(num);
            num += 1;
        }

        // Pushing above created 1D vector
        // to create the 2D vector
        vec.push_back(v1);
    }

    // Displaying the 2D vector
    for (int i = 0; i < vec.size(); i++)
    {
        for (int j = 0; j < vec[i].size(); j++)
            cout << vec[i][j] << " ";
        cout << endl;
    }
    return 0;
}

 

Deletion or Removal: Using pop_back() function

Below is the C++ program to show how to perform deletion in a 2D vector using the pop_back() function:

// Welcome to favTutor
// Deletion program in C++ in a 2D vector

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

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

    // Removing elements from the
    // last row of the vector
    vec[2].pop_back();

    // Removing elements from the
    // second last row of the vector
    vec[1].pop_back();
    vec[1].pop_back();

    // Displaying the 2D vector
    for (int i = 0; i < 3; i++)
    {
        for (
            auto it = vec[i].begin();
            it != vec[i].end(); it++)
            cout << *it << " ";
        cout << endl;
    }
    return 0;
}

 

How to traverse in a 2D vector?

Below is the C++ program to show how to traverse in a 2D vector using iterators :

// Welcome to favTutor 
// C++ code to traverse in a 2D vector

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

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

	// Traversing 
	for (int i = 0; i < 3; i++) {
		for (
			auto it = vec[i].begin();
			it != vec[i].end(); it++)
			cout << *it << " ";
		cout << endl;
	}

	return 0;
}

 

Conclusion

Problems related to matrices, graphs, and other two-dimensional objects involve using 2D vectors to the great extent. So it is very crucial to have a deep understanding of how to declare, initialize, traverse, insert and remove elements in or from a 2D vector.

I hope this article helped you to understand 2D vectors in C++ step by step. Keep Learning!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.