c++ - 关于 vector 的困惑

标签 c++ vector constructor insert

<分区>

我很想知道下面的代码是什么意思

我只是想知道它是如何工作的。

vector<int> lotteryNumVect(10); // I do not understand this part.

int lotteryNumArray[5] = {4, 13, 14, 24, 34}; // I understand this part.

lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray,
                      lotteryNumArray + 3); // I do not understand this part.

cout << lotteryNumVect.at(2) << endl; // I understand this part.

最佳答案

这个声明

vector <int> lotteryNumVect(10);

声明一个由 10 个元素初始化为零的 vector 。

那就是使用了构造函数

explicit vector(size_type n, const Allocator& = Allocator());

3 Effects: Constructs a vector with n default-inserted elements using the specified allocator.

构造函数的第二个参数有一个默认参数,因此您可以调用构造函数,仅指定要在 vector 中创建的元素数。

这个语句

lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray,
                      lotteryNumArray + 3);

在 vector 的开头插入数组中的 3 个元素。

因此 vector 看起来像

4, 13, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 

关于c++ - 关于 vector 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381531/

相关文章:

c++ - 带转发的initializer_list 的模板参数推导

c++ - 如何通过复用单个 API 函数调用不同的操作?

r - 根据命名向量 (R) 更改列名

c++ - 模拟以退出代码 : 132 终止

c++ - DLL GetProcAddress 问题 - 另一个运行时检查失败

c++ - 初始化一个 C 字符串 vector

c++ - 使用 int vector 元素作为输入的递归方法类

c# - 为什么我可以更改私有(private)静态只读字段但不能更改公共(public)字段?

java - 将构造函数参数传递给 JAVA 方法

javascript - this 在 underscore.js 的函数 "_"中