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;
}
6
  • 1
    it doesn't work. Commented Dec 1, 2017 at 6:17
  • care to explain? Commented Dec 1, 2017 at 6:21
  • Indeed, since the vector’s size is 0. You can use seqArr[i].push_back(0); instead. Commented Dec 1, 2017 at 6:22
  • 1
    vector<int> seqArr[n]; require Variable-Length-Array (VLA) which is a C11 feature not available in C++ Commented Dec 1, 2017 at 6:23
  • 4
    Why don't you try vector<vector<int> >? Commented Dec 1, 2017 at 6:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.