2D Vector in C++: A Practical Guide With Methods

2D Vector in C++: Methods Explained

You should be aware of the dynamic arrays in different programming languages. While learning C programming language, you must have gone through it. But, have you ever thought about the concept of two-dimensional vectors or “2D vectors in C++” programming language?

The Vectors in CPP act like the Dynamic Array Concept. That means the CPP Vector can be expanded or reduced as per the size needed. You can also get a Linked List-like feeling while working on the vectors as there are many similarities present between them.

In this article, all the details of the two-dimensional vector will be discussed along with some very important sample examples. But before we start implementing the sample examples related to two-dimensional vectors, we should know its basics.

So, let us start our discussion.

Summary or Key Highlights: 

  • The Vector is the dynamic array of the C++ programming language.
  • There are two types of vectors present in C++, the Normal & 2D Vector.
  • There are two ways present to declare a 2D vector in C++.
  • You can directly enter values into 2D Vector or add them using Column & Row Numbers.
  • Sorting, Searching & Traversing on C++ 2D Vectors can also be done.
  • On 2D Vector, we can perform some major operations.

What Is A Vector Array In C++ Programming Language?

Vector is a special concept in the C++ programming language. It is moreover similar to the array Data Structures concept in different programming languages. But there is an extra feature present. The vector in C++ represents the dynamic properties of elements inside.

				
					// Example Of Single Vector Declaration
vector<int> v1 = {1, 2, 3, 4}; // Initializer List Method
vector<int> v2{1, 2, 3, 4}; // Uniform Initialization Method
vector<int> v3(10, 5); // Ten Times 5 Will Add
return 0;

				
			

That means the vector size can be increased dynamically with the inputs from the user. It is moreover like the linked list where the number of elements can be stretched without losing memory. We should include the vector header file to use the user-defined size.

Did you face any difficulty understanding the code? Don’t worry, you can get help from reliable C++ programming homework experts and clear all your doubts.

CPP 2D Vector Initialization:

A two-dimensional vector is the extended version of a single-dimensional vector. In the two-dimensional vector, the vector concept is used. One is used for making the row & another is used for making the column. It is the same concept just like the 2D array Data Structures in other Programming Languages.

				
					// Example Of Normal 2D Vector Declaration Process
vector<vector<int>> v; // 2D Vector Initialization

				
			

Just, the difference is that the two-dimensional vector is dynamic. That is the reason, it is more convenient to use. Whenever any elements are deleted or inserted into the 2D vector, it will automatically resize itself.

How To Declare 2D Vector In CPP?

There are mainly three methods present to declare the 2D vector in C++. One of them has already been demonstrated in the above code snippet. 

There are two more methods present by which we can declare the 2D vector.

  • 2D Vector Initialization With Value:

In this case, the 2D vector initialization is done normally, but the values we already provide there. Before moving to the initialization process, the standard template libraries should be included in the program along with the vector header file.

				
					// Example Of 2D Vector Declaration Along With Data
#include<vector>
#include<iostream> 
using namespace std;
int main()
{
	vector<vector<int>> v{{1, 2, 3},{4, 5, 6}};
	return 0;
}

				
			

Here, using the above syntax we will declare a 2D vector int which will collect some values. We will use the braces to indicate the row & column elements inside of the 2D vector.

  • 2D Vector Initialization With Row & Column Values:

 In this case, the 2d vector declaration will not be done simply. Here, we don’t need to show the size of the vector using the vector elements. Rather, we will use the row & column numbers to mark the size. Also, the initialization of vectors in C++ can be a little tricky. You can learn about the methods used to initialize a vector, which will make your understanding of vectors more easy.

				
					public class Main
{
	public static void main(String[] args) {
System.out.println("Printing Started Untill Encounter Of Break: ");
int n= 8;
for (int i = 1; i < n; i++) { // Starting A For Loop
if (i == 5){ //Condition To Implement Break Statements
                System.out.println("--Encountered Break--");
                break; // Break Statement
            }
System.out.println(i); // Printing Data
        }
	}
}

				
			

In the above case, the row & column data are declared in a separate variable. Now, we will use two different vector int concepts to declare the overall 2D vectors in C++ programming language. But it is quite difficult to declare.

What Is The Process To Traverse Through 2D Vector In C++? How To Print A 2D Vector In CPP?

Traversing through the two-dimensional vector is a very simple process to execute. It is like going through the 2D array. Like the 2D array, we should declare the nested for loop to traverse in the 2D vector. But we should declare one first.

Code for declaration:

				
					#include<vector> 
#include<iostream> 
using namespace std;
int main()
{
	vector<vector<int>> zap{{20, 07},{23, 20}}; // Initialization Of Vector Inside Vector
    cout << "Traversal Of 2D Vector: " << endl;
    for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
    {
        for (int j = 0; j < zap[i].size(); j++) // Inner Loop For Displaying Vector
            cout << zap[i][j] << " ";
        cout << endl;
    }
	return 0;
}

				
			

Steps of The Program: 

  • At first, the Vector Header File Libraries will be included in the program.
  • A sample vector along with the data will be provided in the program.
  • Two nested loops will be declared. There will be the Outer & Inner Loop.
  • The Outer Loop will consider the row, and the Inner Loop will print every element there.

Output: 

Traverse Through 2D Vector In C++

As this is a traversing operation or in simple words, we are going to print the 2D Vector in C++, the necessary result will be in front of us. As it is a print operation, the data that we have provided in the 2D Vector will be printed.

How To Sort 2D Vector In CPP?

Sorting means any data is present in a random order and we are going to place them in a particular pattern. In most cases, the Sorting Algorithm makes any unsorted numbers in the Ascending Manner. Here, we are going to do the same thing.

In the CPP 2D Vector, there is no particular sorting algorithm is present. Either some sort an single Row or any single Column. That sometimes failed to fulfill the purpose of sorting. So, you are going to make a program to Sort the CPP 2D Vector entirely, not any single Row and Column.

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

int main() {
    vector<vector<int>> zap = {{7, 8, 9},{4, 5, 6},{1, 2, 3}}; // Unsorted 2D Vector
    
    sort(zap.begin(), zap.end()); // Sorting The 2D Vector

    // Printing The 2D Vector
    cout << "Sorted 2D vector:" << endl;
    for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
    {
        for (int j = 0; j < zap[i].size(); j++) // Inner Loop For Displaying Vector
            cout << zap[i][j] << " ";
        cout << endl;
    }


    return 0;
}


				
			

Steps of The Program: 

  • At first, the Vector & Algorithm Header Files are taken into the program for further use by libraries.
  • A 2D Vector is declared along with some values in different order.
  • Now, the Sort() function will be used. It will check the order from the Beginning to the End of the 2D Vector. It will make it in a sorted manner.
  • Now, we are going to Traverse or Print the values in the 2D Vector as we have discussed earlier.

Output:

Sort Vector Output

From the above output, it should become clear to us the way to Sort 2D Vector in C++ Programming Language. You can see the values that are in the random order are now in the proper manner. So, the purpose of the above program is fulfilled with the Sort() Function.

What Are The Major Operations Can Be Done On 2D Vectors In C++?

The above discussion will be enough to clear your basic doubts related to the 2D vectors in C++ programming language. Now, we should understand some of the major operations that can be done on the 2D vectors. They are the following:

  1. Insert Vector’s Elements Using push_back() Method
  2. Remove Elements Using pop_back() Method
  3. Find Any Element Using the at() function.
  4. Get the Total Number of Elements Using size() Function.
  5. Check whether the Vector is Empty or not using the empty() Function.

Let us know all of them one by one briefly.

  • How To Insert Vector’s Elements Using Push_back() Method?

The push_back() is the built-in function present with the standard template library for doing operations on the 2D vector. It is an operation that can be done with the help of another vector. One vector data will be inserted inside of another vector.

The same operation can be done with the default value. It is like the append operation that adds some data into the empty container one by one. Using the method, in one empty vector, we will insert data from another vector.

General Syntax: new-vector-name.push_back(old-vector-name);

Code To Implement Use Of The Push_back() Method:

				
					
#include<vector> 
#include<iostream> 
using namespace std;
int main()
{
    vector<vector<int>> zap; // 2D Vector Initialization
    vector<int> one = {20, 07, 20, 23}; // 1D Vector Initialization With Values
    zap.push_back(one); // Pushing The Data


    cout << "The 2D Vector Data Is: ";
    for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
    {
        for (int j = 0; j < zap[i].size(); j++) // Inner For Loop For Displaying Vector
            cout << zap[i][j] << ",";
    }
    return 0;
}

				
			

Steps Of The Program:

  1. At first, the declaration of the 2D vector will be done without providing any value to it.
  2. Now, one simple single-dimensional vector will be declared where some values will be provided.
  3. Now, we will share the value of that single vector with that 2D vector. That is the reason, the single vector name is present inside of the braces for copying purposes.
  4. Now, we will traverse the 2D vector to print the values from it. It will print all the elements of it.

Output:

Use Of The Push_back() Method Output

From the above output, we can see that the insertion into the second vector is done from the first vector. Here, the vector dimensions are irrelevant because the first vectors assign values to the second vector without error.

  • How To Remove Elements Using Pop_back() Method?

Just like the inbuilt function present to add elements inside of a dynamic array or 2D vector, there is also one inbuilt function present that helps in removing elements. That is known as the pop_back() method. And it can be used for other two-dimensional objects also.

Here, the complete play is executed with the vector index number or integral index. The zero index number represents the number of int rows present in the program. The zero index is for the first row, the first index is for the second row & the second index is for the third row.

General Syntax: vector-name[index-number].pop_back();

Code To Implement Use Of The Pop_back() Method:

				
					#include<vector> 
#include<iostream> 
using namespace std;
int main()
{
    vector<vector<int>> zap{{20, 07},{23, 20}}; // Initialization Of Vector Inside Vector
    cout << "Original 2D Vector: ";
    for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
    {
        for (int j = 0; j < zap[i].size(); j++) // Inner Loop For Displaying Vector
            cout << zap[i][j] << " ";
    }
    cout << endl;
    zap[0].pop_back(); // Removing Last Element Of First Row
    zap[1].pop_back(); // Removing Last Element Of Second Row
    cout << "2D Vector After Element Removing: "<< endl;
    for (int i = 0; i < zap.size(); i++) // Outer For Loop For Displaying Vector
    {
        for (int j = 0; j < zap[i].size(); j++) // Inner For Loop For Displaying Vector
            cout << zap[i][j] << endl;
    }
    return 0;
}

				
			

Steps Of The Program:

  1. Here, the implementation of the two-dimensional vector will be done along with providing some values that are used in creating matrices.
  2. Now, we traverse through the two-dimensional vector & print all the default values that have been provided.
  3. Now, we will use the above basic syntax for removing elements one by one. First, the last element of the first row will be removed. Then, the last element of the second row will be removed in the same manner.
  4. Now, the data will be again printed inside the console. In the result data, the removed elements will not be present.

Output:

Use Of The Pop_back() Method Output

From the above output, we can see that with the removal of elements from the data structures, the two-dimensional vector works properly. In the first case, it prints all the data. And in the second case, after removing elements the remaining data is printed.

  • How To Find Elements Using At() Method In CPP 2D Vector? 

The at() function is the inbuilt function that comes with the Vector Library. We have to use the at() Function in the same way, we were doing things previously. The use of the at() function is as easy as you can think. 

Syntax: vector-name.at(Row Number).at(Column Number)

Code To Implement At() Function In The 2D Vector of C++ Programming Language: 

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

int main() {
    vector<vector<int>> zap = {{1, 2, 3},{4, 5, 6}}; // Creating A 2D Vector

    // Accessing Elements Using AT() Operation
    int e = zap.at(0).at(1); 
    cout << "Row 0 & Column 1 Element: " << e; // Print The Result

    return 0;
}


				
			

Steps of the Program: 

  • Declare one 2D Vector in the program along with some values previously.
  • Use the above syntax & get the element number stored in one variable.
  • Print the variable to get the actual result we want.

Output: 

Webp- 3- At() Function Output

From the above output, we can see that the value is coming as the 2. Here, we are going to access the element at row 1, column 2, so we are getting the result as 2. We have to remember that the indexing starts from 0.

  • How To Find Total Elements Using Size() Method In CPP 2D Vector? 

The Size() function is the important function. Using this function, you can get the number of elements from the Row as well as the Columns. To get the total number of elements in one Vector, we have to use one trick to get.

Syntax for Row: Vector-Name.size

Syntax for Column: Vector-Name.at(Row Number).size()

Code to Demonstrate The Use Of Size Function To Get Size Of Ideal 2D Vector:

				
					
#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<vector<int>> zap = {{1, 2, 3},{4, 5, 6}}; // Creating A 2D Vector
    int r = zap.size(); // Row Number
    int c = zap.at(0).size(); // Column Number
    cout << "Number of Rows: " << r << endl; // Print The Row Result
    cout << "Number of Columns: " << c << endl; // Print The Column Result
    cout << "Total Elements: " << r*c;
    return 0;
}


				
			

Steps of The Program: 

  • Here, the 2D Vector along with some values will be declared in the program.
  • Now, using the above values, we are going to take the number of elements in Row & Column.
  • And as the Vector is Ideal, we will multiply the values to get the total numbers.
  • We will print each value in the program.

Output: 

Size() Function Output

From the above output, it should become clear that the Size() Function will be the best to get the number of elements present in the 2D Vector. Here, the Number of Rows is 2 & Number of Columns is 3. So, there are a total of Six Elements are present.

  • How To Find Empty Status Using Empty() In CPP 2D Vector? 

Like every data structure, there is a also function present to check whether any 2D Vector is empty or not in the C++ Programming Language. The use of the Empty() Function is the easiest among other operations we discussed so far.

Syntax: Vector-Name.empty()

C++ Program to Define The Use of the Empty() Function For 2D Vector:

				
					
#include <iostream>
#include <vector>
using namespace std;
int main() {
    vector<vector<int>> zap = {{1, 2, 3},{4, 5, 6}}; // Creating A 2D Vector

    if (zap.empty()) // If 2D Vector Is Empty
        cout << "The 2D Vector Is Empty" << endl;
    else // If 2D Vector Is Not Empty
        cout << "The 2D Vector Is Not Empty" << endl;
    return 0;
}


				
			

Steps of The Program: 

  • The 2D Vector is declared along with some values to check the Empty() Function.
  • Now, we will use the If-Else Statement.
  • Using the above syntax, if the Vector is empty one data will be displayed.
  • Otherwise, the Not Present Data will come.

Output: 

 Empty() Function Output

From the above output, we can see that the Not Empty Result is coming to the window. In this case, there are certain values are present in the Vector. That is the reason, the If Statement doesn’t execute here & the Else statement gets fulfilled.

Conclusion:

As we saw, it is very important to understand the “2D vectors in C++” concept.

We all think that the Data Structures array concept is superior among all list-like concepts. But the concept like vector, we forget to use. That is the reason, there is a more problems we face while finding a solution to a simple program. If you’re interested in knowing about arrays in other programming languages like Java, then you start with knowing the basic difference between Array vs ArrayList.

It is advisable to clear the basic concept of the C++ programming language. In this topic also, some very basic concepts we have used like the insertion of the header files. If you don’t know the basics & background of such a thing, your knowledge is not going to be so deep that will matter for your future.

Key Takeaways: 

  • Vector works like a dynamic array concept where the size can be changed over time.
  • Using the List Method & Uniform Method, we can declare a 2D vector in C++.
  • We can directly provide values or insert them using the Row & Columns.
  • Traversing or Printing of Vector can only be done with the help of the loops.
  • The Sort() function from the Algorithm is used to sort vectors in any order.
  • We can insert Vector’s Elements using push_back() method
  • We can remove elements using the pop_back() method
  • To Find Any Element in Vector the at() function will be used.
  • We can get the total number of elements using the size() function.
  • We can check whether the vector is empty or not using the empty() function.

Leave a Comment

Your email address will not be published. Required fields are marked *