vector<vector<int>>dp(3);
for(int i = 0; i<3; i++) {
vector<int>price(10);
dp.push_back(price);
}
It is showing error while initialization. Can anyone explain the reason behind this wrong code?
vector<vector<int>>dp(3);
for(int i = 0; i<3; i++) {
vector<int>price(10);
dp.push_back(price);
}
It is showing error while initialization. Can anyone explain the reason behind this wrong code?
If what you intend is declaring an empty two dimensional vector[3][10]
, you can do it at once.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int>> dp(3,std::vector<int>(10));
std::cout<<dp.size(); //3
std::cout<<std::endl<<dp[0].size(); //10
}
Then you can assign values to it by using something like dp[0][4]=12;
or with loops.
This statement
vector<vector<int>>dp(3);
create a vector dp
with 3
default constructed int
vectors and in loop, you are doing
dp.push_back(price);
the push_back()
appends the given vector value to the end of the container. So, after loop, you will end up having dp
vector of size 6
, out of which first 3
are empty vectors and last 3
are vectors of 10
int
elements.
Instead of specifying size
, you can use reserve()
to reserver the storage:
vector<vector<int>>dp;
dp.reserve(3);
for(int i = 0; i<3; i++) {
vector<int>price(10);
dp.push_back(price); // A suggestion: check emplace_back
}
To create a vector of 3
vectors, each having 10
int
elements, you can simply do:
vector<vector<int> >dp (3, vector<int>(10));
Also, if you want to initialise all elements with some value, say -1
, you can do:
vector<vector<int> >dp (3, vector<int>(10, -1));