staircase 2d vector in c++

65 Views Asked by At

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;
    }

}
2

There are 2 best solutions below

0
fabian On

auto doesn't deduce reference resulting in the loop variables creating copies instead of refering to the existing vector elements. Add an & to make sure the loop modifies the elements of the vector<vector<int>> (and to avoid unnecessary copies in the second loop):

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 const& vctr : vec) {
        for (auto it : vctr) {
            cout << it << " ";
        }
        cout << endl;
    }
}
0
andreee On

In the first loop, you need to write for(auto& vectr:vec) (note the reference), otherwise you will be iterating over copies of the vector.