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,

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐