在C++中,可以创建一个预定义大小的数组,例如20 int myarray[20]
.但是,关于向量的在线文档并未显示初始化向量的相似方法:相反,应使用例如初始化向量std::vector<int> myvector (4, 100);
.这给出了大小为4的向量,其中所有元素都是值100.
如何使用预定义的大小初始化向量而没有预定义的值,就像使用数组一样?
Cha*_*had 55
使用构造函数:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
Run Code Online (Sandbox Code Playgroud)