在运行时设置向量的向量大小 [英] Set size of vector of vectors at run time
问题描述
我想知道,如何在运行时设置向量的大小.
I would like to know, how to set the size of vector of vectors at run time.
如果我的尺码固定,我通常会通过
If I have fixed size, i usually do it by
std::vector<std::vector<int>> ref(5);
然后我通过
ref[i].push_back(23); // i = 0,1,...4
现在,如果有兴趣在运行时设置大小,则意味着我想通过命令行参数来获取大小,并以与上述相同的方式推送元素.
Now if am interested to set the size at run time, means, i want to get size through command line argument, and push the elements in the same way as above.
我想通过保持向量开放来声明向量的向量
I thought to do it by declaring the vector of vectors by keeping it open
std::vector<std::vector<int>> ref;
然后推送元素
ref[i].push_back(23);
但是我肯定会错的,因为我得到了错误
But I am sure to be wrong, as I get the error
分段错误(核心已转储)
Segmentation fault (core dumped)
推荐答案
您可以使用std::vector::resize
.如果输入大小大于向量的当前大小而不增加向量的内容,则它将增加向量的容量. (它可能会重新分配向量,但这不会影响您的程序)
You can use std::vector::resize
. It increases the capacity of the vector if input size is greater that current size of vector without changing the content of the vector. (It may reallocate the vector, but that doesn't effect your program)
像您一样初始化载体:
vector<vector<int> > ref;
Initialize the vector as you did:
vector<vector<int> > ref;
现在,当您向后推时,请检查i
是否在向量的当前大小范围内.如果不是,请调整std::vector
的大小,然后调用std::vector::push_back
Now, when ever you push back, check if i
is within current size of vector. If not, resize the std::vector
and then call std::vector::push_back
if(i>=ref.size())
ref.resize(i);
ref[i].push_back(23);
这篇关于在运行时设置向量的向量大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!