简体   繁体   English

在C ++中初始化带有零的向量数组

[英]Initialilze an array of vectors with zeros in C++

I want a array of vectors with 0 as a single element in all the individual vectors. 我想要一个向量数组,其中所有单个向量中的单个元素都为0。 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;
}

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++. 可变长度数组(VLA)是C99的一项功能,在C ++中不可用。 In C++, the size of an array must be known at compile time. 在C ++中,必须在编译时知道数组的大小。

由于可变长度数组不是c ++的一部分,因此我建议使用向量向量,它也解决了初始化问题:

 vector<vector<int>> sequArray(n,{0}); //vector of n vectors, each containing a single 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM