对向量的困惑

Confusion about vectors

本文关键字:向量      更新时间:2023-10-16

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

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

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 个由零初始化的元素的向量。

那就是使用了构造函数

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

3 效果:使用 n 个默认插入的元素构造一个向量 指定的分配器。

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

本声明

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

插入数组中向量 3 元素的开头。

因此,矢量将看起来像

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

解释

  1. 声明vector <int> lotteryNumVect(10);

    这是使用构造函数的示例。 根据cplusplus的说法:

    默认值 (1(:explicit vector (const allocator_type& alloc = allocator_type());

    填充 (2( :explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type());

    范围 (3( :template <class InputIterator> vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());

    副本 (4( :vector (const vector& x);

    因此,vector <int> lotteryNumVect(10);用十个零初始化向量(参见上面的 (1((。vector <int> lotteryNumVect(5, 2);将用五个二初始化向量(参见上面的 (2((。 您可以在此处查看示例以更好地理解。

  2. 声明lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, lotteryNumArray + 3);

    这实际上是通过迭代器插入的。看看这个:

    单元素 (1( :iterator insert (iterator position, const value_type& val);

    填充 (2( :void insert (iterator position, size_type n, const value_type& val);

    范围 (3( :template <class InputIterator> void insert (iterator position, InputIterator first, InputIterator last);

    术语lotteryNumVect.begin()实际上指向lotteryNumVect的第一个元素(参见vector::begin(((。而lotteryNumArraylotteryNumArray+3分别指向lotteryNumArray数组的第一个和第三个元素。 因此,基本上lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, lotteryNumArray + 3);lotteryNumArray的前三个元素插入到向量lotteryNumVect的开头。


进一步阅读 std::vector

  • 普罗斯加斯
  • CPP 首选项
  • GeeksforGeeks

如何在 cplusplus 上导航:

  • 页眉:cplusplus.com/reference/<type header name here>
    示例:cplusplus.com/reference/iostream/
  • 函数/容器/关键字:
    cplusplus.com/reference/<the header which contains it>/<function/container/keyword name>示例:cplusplus.com/reference/iostream/cin/
  • 成员函数/变量:
    cplusplus.com/reference/<the header which contains it>/<function/container/keyword name>/<member variable/function name>/示例:cplusplus.com/reference/string/string/size/

或者,你可以谷歌它。在这种情况下,您将在搜索结果中获得所有三个站点,并且可能会获得更好的结果。

让我们一步一步地看一

vector<int> lotteryNumVect(10);
  • 创建int秒的向量,将大小设置为 10。
lotteryNumVect.insert(lotteryNumVect.begin(), // Place to insert stuff
lotteryNumArray,        // Pointer to start of thing to insert
lotteryNumArray + 3);   // Pointer to end of stuff to insert
  • lotteryNumVect中插入前 3 件事lotteryNumArray