如何创建用户定义大小但没有预定义值的向量? [英] How to create a vector of user defined size but with no predefined values?

查看:28
本文介绍了如何创建用户定义大小但没有预定义值的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,可以使用 int myarray[20] 创建一个预定义大小的数组,例如 20.但是,有关矢量的在线文档 并未显示初始化矢量的类似方式:相反,vector 应该初始化为,例如,std::vector;myvector (4, 100);.这给出了一个大小为 4 的向量,所有元素的值都是 100.

In C++ one can create an array of predefined size, such as 20, with int myarray[20]. However, the online documentation on vectors doesn'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.

如何像数组一样仅使用预定义的大小而不使用预定义的值来初始化向量?

How can a vector be initialised with only a predefined size and no predefined value, like with arrays?

推荐答案

使用构造函数:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

这篇关于如何创建用户定义大小但没有预定义值的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆