Also referred to as vector of vectors, 2D vectors in C++ form the basis of creating matrices, tables, or any other structures, dynamically. Before arriving on the topic of 2D vectors in C++, it is advised to go through the tutorial of using single-dimensional vectors in C++.
It would be impossible for us to use vectors in C++, if not for the header files that are included at the beginning of the program. To make use of 2D vectors, we include:
#include<vector>
Instead of including numerous kinds of Standard Template Libraries (STL) one by one, we can include all of them by:
#include<bits/stdc++.h>
Firstly, we will learn certain ways of initializing a 2-D vector. The following code snippet explains the initialization of a 2-D vector when all the elements are already known.
`#include<iostream>`
`#include<vector>`
`**using**` `**namespace**` `std;`
`**int**` `main(){`
`vector<vector<``**int**``>> v {{1, 0, 1}, {0, 1}, {1, 0, 1}};`
`**for**``(``**int**` `i=0;i<v.size();i++){`
`**for**``(``**int**` `j=0;j<v[i].size();j++)`
`cout<<v[i][j]<<``" "``;`
`cout<<endl;`
`} `
`}`
After running the above code, we get the following output:
1 0 1
0 1
1 0 1
The use of 'vector<vector<>>'
symbolizes that we are working on a vector of vectors. Each value inside the first set of braces, like '{1, 0, 1}'
and '{0, 1}'
are vectors independently.
Note: To create 2D vectors in C++ of different data-type, we can place the data-type inside the innermost angle brackets like
<char>
.
Since we are working on a two-dimensional data structure, we require two loops for traversing the complete data structure, efficiently. The outer loop moves along the rows, whereas the inner loop traverses the columns.
Note: The
'size()'
function provides the number of vectors inside the 2D vector, not the total number of elements inside each individual vectors.
#c #cplusplus #programming-c