C++ 如何创建用户定义大小但没有预定义值的向量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10559283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a vector of user defined size but with no predefined values?
提问by Naphstor
In C++ one can create an array of predefined size, such as 20, with int myarray[20]
. However, the online documentation on vectorsdoesn't show an alike way of initialising vectors: Instead, a vector should be initialised with, for example, std::vector<int> myvector (4, 100);
. This gives a vector of size 4 with all elements being the value 100.
在 C++ 中,可以创建一个预定义大小的数组,例如 20,使用int myarray[20]
. 然而,关于向量的在线文档并没有显示初始化向量的类似方式:相反,向量应该初始化,例如,std::vector<int> myvector (4, 100);
. 这给出了一个大小为 4 的向量,所有元素的值都是 100。
How can a vector be initialised with only a predefined size and no predefined value, like with arrays?
如何像数组一样仅使用预定义的大小而不使用预定义的值来初始化向量?
回答by Chad
With the constructor:
使用构造函数:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;