使用vector :: insert()|在vector中插入元素 C ++ STL

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值