Doubt in C++ Vectors

The following program works well (using vector<vector > a)

#include<bits/stdc++.h>
 using namespace std;
 void print(vector<vector<int> > a)
 {
     for(int i=0;i<a.size();i++)
     {
         for(auto x:a[i])
             cout<<x<<" ";
         cout<<"\n";
     }
 }
 int main()
 {
     vector<vector<int> > a(2);
     cout<<a.size()<<"\n";
     a[0].push_back(1);
     a[1].push_back(2);
     print(a);
 }

The output is
2
1
2
Now if I create a array of vector (vector a[]), the following program gives error

#include<bits/stdc++.h>
    using namespace std;
    void print(vector<int> a[])
    {
        for(int i=0;i<a.size();i++)
        {
            for(auto x:a[i])
                cout<<x<<" ";
            cout<<"\n";
        }
    }
    int main()
    {
        vector<int> a[2];
        cout<<a.size()<<"\n";
        a[0].push_back(1);
        a[1].push_back(2);
        print(a);
    }

What changes needs to be done in the above program to get the same output?

Few Tips:

  • Never send a whole vector. Send it’s reference otherwise that adds overhead and increases time.

  • Add this code snippet at the top inside your main(read this here why):

      ios_base::sync_with_stdio(false);
      cin.tie(0);
    
1 Like

‘a’ is an array of vectors. It has no method called size. You’ll have to know the size beforehand. This new code will work

#include<bits/stdc++.h>
    using namespace std;
    void print(vector<int> a[])
    {
        for(int i=0;i<2;i++)
        {
            for(auto x:a[i])
                cout<<x<<" ";
            cout<<"\n";
        }
    }
    int main()
    {
        vector<int> a[2];
        cout<<"2"<<"\n";
        a[0].push_back(1);
        a[1].push_back(2);
        print(a);
    }
1 Like

Understood. Thank You :slightly_smiling_face: