Search code examples
c++vector

Why 0 is in the output?


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {
   vector<vector<int> >a(2);
    for(int i=0;i<2;i++)
    {
        int m;
        cout<<"Enter number of elements on the row:"<<endl;
        cin>>m;
        vector<int> b(m);
        cout<<"Element:"<<endl;

         for(int j=0;j<m;j++)
         {
             int k;
             cin>>k;
             b.push_back(k)//if i use b[j]=k; here the zeros don't appear.
             //cout<<b[j];
         }
         a.push_back(b);
    }

    for(unsigned int i=0;i<a.size();i++)
        {
            for(unsigned int j=0;j<a[i].size();j++)
                cout<<a[i][j]<<" ";
            cout<<endl;
        }
    return 0;
}

Why does zero appear in the output?

The output should be without zeros.

In the second push_back function, if I use b[j] then zeros don't appear.


Solution

  • You are initializing a with 2 blank vectors in it and then pushing 2 populated vectors into it.

    And you are initializing b with m number of default zeros and then pushing m user-input integers into it.

    You should not be initializing either vector with a value in its constructor. That pushes default values into the vector, which is throwing off your results. In this case, simply remove the constructor values and let push_back() handle the adds for you.

    If you want to preallocate a vector's memory without adding values to it, use its reserve() method instead, eg:

    vector<vector<int> >a;
    a.reserve(2);
    ...
    vector<int> b;
    b.reserve(m); 
    

    Otherwise, if you do use the constructor to pre-fill the vectors with defaults, then you need to change your loops to use vector::operator[] instead of vector::push_back(), eg:

    vector<vector<int> >a(2);
    for(int i=0;i<2;i++)
    {
        ... 
        vector<int> b(m);
    
        for(int j=0;j<m;j++)
        {
            ...
            b[j] = k;
        } 
    
        a[i] = b;
    }