1

I want a array of vectors with 0 as a single element in all the individual vectors. Is there a much more efficient way? does this work?

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){

        int lastAnswer = 0;
        int n,q;
        cin >> n >> q;
        vector<int> seqArr[n];
        for(int i=0;i<n;i++)
        {
                fill(seqArr[i].begin(),seqArr[i].end(),0);
        }
return 0;
}
Guillaume Gris
  • 2,135
  • 17
  • 34
poda_badu
  • 159
  • 7

2 Answers2

7

You should use a vector if you want an array with a variable length:

vector<vector<int>> seqArr(n);
for (int i = 0; i < n; ++i)
{
    seqArr[i].push_back(0);
}

or simply

vector<vector<int>> seqArr(n, vector<int>(1, 0));   // n vectors with one element 0

Variable-Length-Array (VLA) is a C99 feature that is not available in C++. In C++, the size of an array must be known at compile time.

Mihayl
  • 3,821
  • 2
  • 13
  • 32
2

As variable length arrays are not a part of c++, I'd recommend using a vector of vectors, which also solved your initialization problem:

 vector<vector<int>> sequArray(n,{0}); //vector of n vectors, each containing a single 0
MikeMB
  • 20,029
  • 9
  • 57
  • 102