Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
2D vectors
2.1.
Implementation 1
2.2.
Implementation 2
3.
Vector of vectors in c++
3.1.
Insertion in vector of vectors in c++
3.2.
Implementation of insertion function
3.3.
Deletion in vector of vectors in c++
3.4.
Implementation of deletion function
3.5.
Traversal of vector of vectors in c++
3.6.
Implementation of traversal of vector of vectors in c++
4.
Frequently Asked Questions
4.1.
In C++, what are the main functions of vector?
4.2.
Can we add the elements in the vector from the front?
4.3.
Define iterator in C++.
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Working with vectors of vectors in c++

Author Ashish Sharma
1 upvote

Introduction

A vector is a dynamic array that is built into a standard C++ library. This vector class can grow in size dynamically. The elements are arranged in a continuous manner so that iterators can traverse them. To learn more about vectors, you can visit here.

C++ Vectors

In this article, we will see an introduction to vectors, 2D vectors, vector of vectors in c++, examples of vectors, and implementation in detail.

2D vectors

A vector of the vector is a 2D vector. A 2D vector is like a 2D array which can be declared and assigned values.

Now, let’s understand the 2d vectors with the help of an implementation.

Implementation 1

/* Program to demonstrate a 2D vector where
each of its elements is of a different size.*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
	/*
	We initialize a 2D vector
	named "vect" on line 16 with
	different number of values
	in each element.
	*/
	vector<vector<int>> vec{
		/* Element one with two values in it. */
		{'a', 'b'},
		/* Element two with three values in it. */
		{'c', 'd', 'e'},
		/* Element three with four values in it. */
		{'f', 'g', 'h', 'i'}};
	/*
	Now we will print the vector that we
	just defined using the simple
	nested for loops.
	*/
	for (int m = 0; m < vec.size(); m++)
	{
		for (int k = 0; k < vec[m].size(); k++)
		{
			char c = (char)vec[m][k];
			cout << c << " ";
		}
		cout << "\n";
	}
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Time complexity

O(N*N) since N is the size of the vector.

Space complexity

O(N) as N is the size of the vector.
 

2D vectors are commonly depicted as a matrix with "rows" and "columns". They are 2D vector elements under the hood.

We then establish an integer variable called "row," followed by an array called "column," which will hold the size of the row. We will then proceed to initialize the memory of each row by the column size.

Implementation 2

// Program to insert into a vector of vectors in c++
// CPP program
#include <iostream>
#include <vector>
using namespace std;
int main()
{
	int row;
	int col;
	cout << "Enter the number of row and column respectively\n";
	cin >> row >> col;
	/*
	Create a vector containing "n"
	vectors each of size "m".
	*/
	cout << "2D vector Matrix after inserting the values\n";
	vector<vector<int>> vect(row, vector<int>(col));
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			vect[i][j] = j + i + 1;
		}
	}
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			cout << vect[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Time complexity

O(row*col) as we have used a nested loop to build and print a matrix.

Space complexity

The space complexity is O(N), where N is the size of the vector.

Read More - Time Complexity of Sorting Algorithms

Vector of vectors in c++

The vector of vectors in c++ is the two-dimensional vector having an unknown number of rows, each of which is a vector. Each vector index maintains a vector that can be traversed and accessed by iterators. It's like an Array of Vectors but with dynamic attributes.

Syntax:

vector<vector<data_type>> vect;

 

Example:

vector<vector<char>> vect{ { 'a','b','c'}, 

                                             { 'd','e','f'}, 

                                             { 'g','h','i','j' } }; 

where, vect is the vector of vectors with different number of elements in different rows

Insertion in vector of vectors in c++

We can insert the elements using push_back() function in c++.let’s discuss how to implement the vector of vectors in c++.

Syntax:

vector_name.push_back(value)


Example:

v1 = {‘a’, ‘b’,’c’}

v2 = {‘d’,’e’,’f’}

v1.push_back(v2);

push_back() function pushes the vector v2 with v1, and then v1 becomes {{‘a’,’b’,’c’},{’d’,’e’,’f’}}.

Implementation of insertion function

// Program to insert into a vector of vectors in c++
#include <iostream>
#include <vector>
using namespace std;

int main()
{
	int ROW, COL;
	cout << "Enter the number of row, column respectively\n";
	cin >> ROW >> COL;
	// Initializing the vector of vectors
	vector<vector<int>> vec;

	// Elements to insert in column
	int num = 10;
	// 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 += 5;
		}
		// Pushing back above 1D vector
		// to create the 2D vector
		vec.push_back(v1);
	}
	cout << "Matrix after inserting the elements will be \n";
	// Displaying the 2D vector
	for (int k = 0; k < vec.size(); k++)
	{
		for (int j = 0; j < vec[k].size(); j++)
			cout << vec[k][j] << " ";
		cout << endl;
	}
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

OUTPUT

Time complexity

O(row*col), as we have used a nested loop to build and print a matrix.

Space complexity

The space complexity is O(N), where N is the size of the vector.

Deletion in vector of vectors in c++

We can delete the elements using pop_back() function in c++.let’s discuss how to implement the vector of vectors in c++.

Syntax:

vector_name[row_position].pop_back()


Example:

Let’s create a vector of vector in c++ for representing the deletion function in vector in c++.

Vector vec={{‘a’,’b’,’c’},{‘d’,’e’,’f’},{‘g’,’h’,’i’}}

v[2].pop_back()


It will pop the ‘i’ element from the vector as the pop operation always delete the elements from the bottom row to the top row.

Implementation of deletion function

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

int main()
{
	vector<char> v;

	v.push_back('a'); // Insert element 1.
	v.push_back('b'); // Insert element 2.
	v.push_back('c'); // Insert element 3.

	cout << "vector before deletion of the element\n";
	for (int j = 0; j < v.size(); j++)
	{
		cout << v[j] << " ";
	}
	// Now a vector(v) has 2 elements in it, with size 3
	v.pop_back(); // This method will help to remove the last element

	cout << "\nvector after deletion of the element\n";
	for (int j = 0; j < v.size(); j++)
	{
		cout << v[j] << " ";
	}
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

output

Time complexity

O(row*col) as we have used a nested loop to build and print a matrix.

Space complexity

The space complexity is O(N), where N is the size of the vector.

Traversal of vector of vectors in c++

We can traverse the vector with the help of an iterator. In the below section, we will discuss how to traverse in vector.
Syntax 

for j in [0, n)
{
    for (iterator i = v[j].begin();
         i != v[j].end(); i++) 
   {
        // Operations which needs to be done
        // For example to print
        print(*i)
    }
}

Implementation of traversal of vector of vectors in c++

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

// Driver Method
int main()
{
	// Initializing 2D vector "vect" with
	// sample values
	vector<vector<char>> vect{{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}};
	cout << "Vector after the traversing\n";
	// Displaying the 2D vector
	for (int i = 0; i < 3; i++)
	{
		for (auto iterator = vect[i].begin();
			 iterator != vect[i].end(); iterator++)
			cout << *iterator << " ";
		cout << endl;
	}
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

output

Time complexity

O(row*col) as we have used a nested loop to build and print a matrix.

Space complexity

The space complexity is O(N), where N is the size of the vector.

Frequently Asked Questions

In C++, what are the main functions of vector?

A vector is a sequence container class that implements dynamic array, which indicates that its size changes as elements are added. A vector holds its items in contiguous memory locations and allocates the memory as needed during execution.

Can we add the elements in the vector from the front?

Moving all the other parts back means adding to the front of a vector. If you want to perform insertion from front, you should probably use list or deque. 

Define iterator in C++.

An iterator is a pointer-like object that points to an element within the container. Iterators can be used to traverse the container's contents. They can be compared to a pointer that is pointing to a certain position, and we can use them to retrieve information at that address.

Conclusion

In this blog, you learned vector of vectors in c++. All the important topics related to vector of vectors in c++ were covered in detail. 
After reading about c++ vector erase, are you not feeling excited to read/explore more articles on c++? Don't worry; Coding Ninjas has covered other articles also. If you want to check out articles related to c++ then you can refer to these links, NaN in C++New and delete operator in c++Scope resolution operator vs this pointer, Dynamic Binding in C++

Recommended Reading: 

Turbo C++
Refer to our Guided Path on Coding Ninjas Studio to increase your knowledge in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

If you want to test your coding skills, you can check out the mock test series and can participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.
Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass