We know that there are two-dimensional arrays, but there are also two-dimensional vectors and that’s what we’re going to talk about today’s cpp::daily.
Vector vector is a two-dimensional vector with a variable number of lines, where each line is a vector. Each array index stores an array that can be traversed and accessed using iterators. It is similar to an array of vectors, but with dynamic properties.
In the future we will have content about libraries that make use of advanced concepts of Mathematics Arrays and Determinants that are generally used to map images, so let’s see how we write a two-dimensional vector now.
When you want to create a multidimensional array you use it like this, for example:
So if you want to print the number 52, it would be: std::cout << array[1][2]
.
Two-dimensional vectors work in much the same way only the performance is superior. The same code above using vectors would be:
#include <vector>
This is a two-dimensional vector, so if you want to print the number 52 as well, it would be:
If you want to print all the values of this vector you can create a nested loop, for example:
The output will be:
Displaying each position of the elements:
What if you want to add one more coordinate to this vector? Just use push_back()
, example:
Before the elements are printed by the for loop.
And if you want to remove the last one added or not, just use pop_back()
:
Final code: