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)
这个说法
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)
声明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))。您可以在此处查看示例以更好地理解。
声明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())。而lotteryNumArray
和lotteryNumArray+3
分别指向lotteryNumArray
数组的第一个和第三个元素。因此,基本上lotteryNumVect.insert(lotteryNumVect.begin(), lotteryNumArray, lotteryNumArray + 3);
将的前三个元素插入lotteryNumArray
到vector的开头lotteryNumVect
。
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。届时,您将在搜索结果中获得所有三个站点,并且结果可能会更好。
归档时间: |
|
查看次数: |
166 次 |
最近记录: |