c++ - 声明后在 C++ vector 中分配元素

标签 c++ vector resize dynamic

请引用下面的代码和注释:

vector<int> v1(10);
cin>>v1[0]; // allowed
cin>>v1[1]; // allowed

// now I want v1 to hold 20 elements so the following is possible:

cin>>v1[15]>>v[19]; // how to resize the v1 so index 10 to 19 is available.

最佳答案

您只需在添加新值之前调整 vector 的大小:

v1.resize(20);

关于c++ - 声明后在 C++ vector 中分配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5922797/

相关文章:

r - 在 R 中将向量乘以矩阵应该返回向量

javascript - 在页面调整大小时更改 CSS

C++ 如何从类 cpp 文件创建 .h

c++ - 结构 vector 只返回最后一个值

c++ - 如何在 HLSL DirectX11 C++ 中使用 Texture2DArray

C++: vector <对< vector <整数>,整数>>

r - 在 R 中列出多个向量上的唯一元素

css - 求 CSS 浏览器兼容性信息,使用 left 和 right 设置宽度

jquery - 在 Chrome 中动态调整 &lt;input&gt; 大小失败(适用于 IE/Firefox)

c++ - libc++ 中的 `__gnu_cxx::temporary_buffer`?