In this article will discuss how to create 2D Matrix using vector of vectors in c++.
Requirement
Represent a 2D Matrix using vector in C++ i.e.
1 , 1 , 1 , 1
1 , 1 , 1 , 1
1 , 1 , 1 , 1
1 , 1 , 1 , 1
1 , 1 , 1 , 1
Declaration of 2D vector or vector of vector in C++
std::vector <std::vector<int> > vec2D
Initializing Vector of Vector – 2D vector
A vector can be initialized using parametrized constructor i.e.
std::vector <NUMBER OF ELEMENTS, VALUE OF EACH ELEMENT>
Frequently Asked:
- vector::at() function in C++
- How to fill a vector with random numbers in C++
- How to use vector efficiently in C++?
- vector::insert() function in C++
So,
std::vector<int> (4, 1)
Will create a vector of 4 integers whose values will be 1.
[showads ad=inside_post]
Now to create a vector of 5 vectors in which each vector is initialized as above, we will use following syntax,
std::vector <std::vector > vec2D(5, std::vector(4, 1));
Let’s see the code to initialize and print 2D vector as follows,
std::vector <std::vector<int> > vec2D(5, std::vector<int>(4, 1)); for(auto vec : vec2D) { for(auto x : vec) std::cout<<x<<" , "; std::cout << std::endl; }
Output
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
Iterator over 2D vector in C++
We can iterate over a vector of vector using [][] . Checkout the code below,
for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) vec2D[i][j] = i*j;
Adding a new row in 2D vector
To add a new row, just push_back a new vector in the vector of vector i.e.
vec2D.push_back(std::vector<int>(4, 11));
Complete working Code is as follows,
#include <iostream> #include <vector> int main() { std::vector <std::vector<int> > vec2D(5, std::vector<int>(4, 1)); for(auto vec : vec2D) { for(auto x : vec) std::cout<<x<<" , "; std::cout << std::endl; } std::cout << std::endl; for(int i = 0; i < 5; i++) for(int j = 0; j < 5; j++) vec2D[i][j] = i*j; for(auto vec : vec2D) { for(auto x : vec) std::cout<<x<<" , "; std::cout << std::endl; } vec2D.push_back(std::vector<int>(4, 11)); std::cout << std::endl; for(auto vec : vec2D) { for(auto x : vec) std::cout<<x<<" , "; std::cout << std::endl; } return 0; }
Compile the above code using following command,
g++ –std=c++11 2dvector.cpp
Hi Sir/Mam,
How to convert std::vector<std::vector >> to Matrix in cpp,
If I have some data of vector of vectors ( ex :- std::vector<std::vector >> data)
that data will be convering to matrix of opencv.
Thanks,
ANR .S