-1
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?

Matt
  • 12,848
  • 2
  • 31
  • 53
hidden0
  • 3
  • 5
  • 3
    What error exactly? You need to either remove `(3)` **or** replace `.push_back(...)` with `.[i] = ...` because now your vector ends up with 6 elements, first 3 of them empty. – HolyBlackCat Jan 09 '21 at 19:04
  • 1
    Cannot reproduce the issue. You'll end up a vector `dp` with size `6` of course: the first 3 elements are empty vectors (the elements initialized with the default constructor in the constructor of the outer vector) and the following 3 have size 10... – fabian Jan 09 '21 at 19:08
  • Note: If the goal is a matrix you may find you get higher performance with a single contiguous block masquerading as a 2D structure. [See this linked answer](https://stackoverflow.com/a/2076668/4581301) for a simple way to do that. – user4581301 Jan 09 '21 at 19:35

2 Answers2

2

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.

user814412
  • 70
  • 1
  • 7
1

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));
H.S.
  • 11,654
  • 2
  • 15
  • 32