I was trying to create a stair case like 2d vector with 10 rows and variable columns like this:
1
1 2
1 2 3
.
.
.
1 2 3 4 5 6 7 8 9 10
And I've written this code which surprisingly prints 10 rows of white spaces. What have I done wrong??
#include <iostream>
#include <vector>
using namespace std;
int main(){
int j=1;
vector<vector<int>> vec(10, vector<int>(0));
for(auto vctr:vec){
for(int i = 0;i<j;i++){
vctr.push_back(i+1);
}
j++;
}
for(auto vctr:vec){
for(auto it:vctr){
cout << it << " ";
}
cout << endl;
}
}
autodoesn't deduce reference resulting in the loop variables creating copies instead of refering to the existingvectorelements. Add an&to make sure the loop modifies the elements of thevector<vector<int>>(and to avoid unnecessary copies in the second loop):