How to create a 2D vector in C++
What is a vector in C++?
A vector in C++ is a sequence of containers that represent an array but with the added ability to adjust its size during runtime. The elements in a vector are stored in linear memory locations, which allow for efficient access to any element.
To use the vectors in our program, we use the C++ STL vector library. This library offers a variety of techniques for manipulating and efficiently accessing the elements in the container.
2D vector in C++
To declare a 1D vector, we use the following format:
vector<datatype> variable_name
When working with a 2D vector in C++, we can create it by defining a vector of data type vector. To do this, we will replace datatype with vector<datatype> and declare a variable using the following syntax:
vector<vector<datatype>> variable_name;
Note: Please replace
datatypewith actual data type names such asint,double, etc.
Coding example
Let’s write code for 2D vectors with the dimensions 3x3 below:
#include <iostream>#include <vector>using namespace std;int main(){vector<vector<int>> Arr{{0, 1, 2}, // Row 0 has 1,2,3{3, 4, 5}, // Row 1 has 4,5,6{6, 7, 8} // Row 2 has 7,8,9};for (int i = 0; i < Arr.size(); i++) // Arr.size() will return a size of vector which is 3{for (int j = 0; j < Arr.size(); j++){cout << Arr[i][j] << " ";}cout << endl;}return 0;}
Explanation
-
Lines 7–12: We initialize the 2D vector with the name
Arrand dimensions 3x3. -
Lines 13–20: We use a nested loop to display the vector’s elements on the console.
Free Resources