One way of inserting elements in the vector is by using push_back() function, it simply inserts the new item at the back of the vector and increases its size by 1. In this article, we are going to discuss other methods of inserting the elements in the vector.
在向量中插入元素的一种方法是使用push_back()函数,它只是将新项目插入向量的后面,然后将其大小增加1。在本文中,我们将讨论其他插入元素的方法在向量中 。
Syntax:
句法:
VectorName.insert (position, value);
Here, position is the iterator which specifies the position where you want to insert the element and value is element you want to insert.
在这里, position是迭代器,它指定要插入元素的位置,而value是要插入元素的位置。
Example 1:
范例1:
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialising the vector
vector<int> myvec{ 10, 20, 30, 40, 50 };
//myvec.begin() returns the iterator which points to element 10
//(myvec.begin() + 2) points 2 position ahead of element 10
myvec.insert(myvec.begin()+2,25);
cout << "Vector elements after inserting 25 : ";
for (vector<int>::iterator it = myvec.begin(); it != myvec.end(); it++)
cout << *it << " ";
cout<<endl;
//it insert the element at the front of vector
myvec.insert(myvec.begin(),5);
cout << "Vector elements after inserting 5 : ";
for (vector<int>::iterator it = myvec.begin(); it != myvec.end(); it++)
cout << *it << " ";
return 0;
}
Output
输出量
Vector elements after inserting 25 : 10 20 25 30 40 50
Vector elements after inserting 5 : 5 10 20 25 30 40 50
Note: If you want to add element more than once at specified position than you can use the following syntax:
注意:如果要在指定位置多次添加元素,可以使用以下语法:
VectorName.insert(position, size, value);
Here, size is the parameter in the insert function which specifies the number of times a specified value is inserted.
在此, size是插入函数中的参数,它指定插入指定值的次数。
Example 2:
范例2:
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialising the vector
vector<int> myvec{ 10, 20, 30, 40, 50 };
//insert the element at the front of vector 3 times
myvec.insert(myvec.begin(),3,5);
cout << "Vector elements after inserting 5 three times: ";
for (vector<int>::iterator it = myvec.begin(); it != myvec.end(); it++)
cout << *it << " ";
return 0;
}
Output
输出量
Vector elements after inserting 5 three times: 5 5 5 10 20 30 40 50
翻译自: https://www.includehelp.com/stl/insert-elements-in-vector-using-vector-insert.aspx