关于向量的困惑

Zav*_*Zav 6 c++ constructor insert vector

我想知道以下代码的含义

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

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.
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 7

这个说法

vector <int> lotteryNumVect(10);
Run Code Online (Sandbox Code Playgroud)

声明一个向量,该向量包含用零初始化的10个元素。

那就是使用构造器

explicit vector(size_type n, const Allocator& = Allocator());
Run Code Online (Sandbox Code Playgroud)

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

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

这句话

lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray,
                      lotteryNumArray + 3);
Run Code Online (Sandbox Code Playgroud)

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

因此,向量将看起来像

4, 13, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 
Run Code Online (Sandbox Code Playgroud)


Mer*_*sud 5

说明

  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到vector的开头lotteryNumVect


进一步阅读std :: vector

如何在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/

或者,您可以使用Google。届时,您将在搜索结果中获得所有三个站点,并且结果可能会更好。