首页 课程 师资 教程 报名

vector删除指定元素的方法

  • 2022-09-16 08:58:45
  • 2480次 星辉

vector删除指定元素的方法有哪些?星辉小编来告诉大家。

1.利用成员函数pop_back()可以删除最后一个元素;

2.利用成员函数erase()可以删除由一个iterator指出的元素;

3.通过STL中的算法库函数remove()删除指定的元素(与list容器自带的成员函数remove() 有较大的区别);

4.vector().swap(x),清空了容器,且释放了内存。

注意

std::remove其实并没有真正从容器中删除元素( 返回的是没有被删除的最后一个元素的位置,* 从first到这个返回值,就是不等于val的所有元素的序列* 。);list的成员函数remove,将list中满足条件的元素真正删除了。

代码

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void initVector(vector<int>& temp_vector)
{
	temp_vector.push_back(1);
	temp_vector.push_back(4);
	temp_vector.push_back(3);
    temp_vector.push_back(2);
	temp_vector.push_back(6);
}
void printVector(vector<int>& temp_vector)
{
	for(int i=0; i<temp_vector.size(); i++)
	{
		cout<< temp_vector[i]<<",";
	}
	cout<<endl;
}
int main()
{
	// 1 pop_back()删除尾部元素
	vector<int> temp;
	initVector(temp);
	cout<<"原始数据为:"<<endl;
	printVector(temp);
	temp.pop_back();
	cout<<"pop_back()之后数据为:"<<endl;
	printVector(temp);
	cout<<"--------------------------"<<endl;
	temp.clear();
	initVector(temp);
	cout<<"原始数据为:"<<endl;
	printVector(temp);
	for(vector<int>::iterator i= temp.begin(); i!= temp.end(); i++)
	{
		if(*i== 2)
		{
			// temp.erase返回的是迭代器
			i= temp.erase(i);
		}
	}
	cout<<"erase()之后数据为:"<<endl;
	printVector(temp);
	cout<<"--------------------------"<<endl;
	temp.clear();
	initVector(temp);
	cout<<"原始数据为:"<<endl;
	printVector(temp);
	temp.erase(std::remove(temp.begin(), temp.end(), 2), temp.end());
	cout<<"使用std::remove之后数据为:"<<endl;
	printVector(temp);
	system("pause");
	return 0;
}

运行结果

原始数据为:
1,4,3,2,6,
pop_back()之后数据为:
1,4,3,2,
原始数据为:
1,4,3,2,6,
erase()之后数据为:
1,4,3,6,
原始数据为:
1,4,3,2,6,
使用std::remove之后数据为:
1,4,3,6,

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交