C++ STL---vector总结(二):增删查改

#include <iostream>
#include <vector>
#include <algorithm>//find
using namespace std;

int main(){
/*add element增加*/
		/*add element method 1---push back从最后面插入*/
	vector<int> v7(1,0);
	for(int i=1;i<5;i++)//after the operation ,elements in v7 are{0,1,2,3,4}
		v7.push_back(i);
		/*add element method 2---insert
		single element (1)	: iterator insert (iterator position可以是迭代器也可以v1.begin()这种位置, const value_type& val);//注意返回值为迭代器
			fill (2)		: void insert (iterator position, size_type n, const value_type& val);
			range (3)		: template <class InputIterator> 
							  void insert (iterator position, InputIterator first, InputIterator last);*/
	vector<int> ::iterator it2;
	it2=v7.insert(v7.begin(),100);	//{100,0,1,2,3,4}.*it2=100,并且返回值为指向插入元素的迭代器!!!
	it2=v7.insert(it2,200);			//{200,100,0,1,2,3,4}.*it2=200,并且返回值为指向插入元素的迭代器!!!
	v7.insert(v7.begin()+1,2,150);			//{200,150,150,100,0,1,2,3,4}
	int arr1[3]={400,350,300};
	v7.insert(v7.begin(),arr1,arr1+3);		//{400,350,300,200,150,150,100,0,1,2,3,4},
	vector<int> v8(2,250);
	v7.insert(v7.begin()+2,v8.begin(),v8.end());//(400,350,250,250,300,200,150,150,100,0,1,2,3,4)

/*delete删除*/
		/*delete element method 1---push back从最后面删除*/
	v7.pop_back();					//(400,350,250,250,300,200,150,150,100,0,1,2,3)
		/*delete element method 2---earse
		iterator erase (iterator position);
		iterator erase (iterator first, iterator last);*/
	v7.erase(v7.begin()+4);			//(400,350,250,250,200,150,150,100,0,1,2,3)
	vector<int>::iterator it3=v7.begin();
	for(;it3!=v7.end();){
		if(*it3==250)
			it3=v7.erase(it3);		//delete 250
		else
			it3++;
	}								//(400,350,200,150,150,100,0,1,2,3)
	v7.erase(v7.begin()+3,v7.begin()+5);//左闭右开(400,350,200,100,0,1,2,3)
/*find查找*/
	//可能因为是用数组方式存储的,从数据结构角度看,
	//数组没有高校的查找方法,不像二叉树,可以直接log的复杂度查找
	vector<int> ::iterator it4;
	it4=find(v7.begin(),v7.end(),1);
	if(it4==v7.end())
		;//cannot find
	else{
		cout<<"successfully find 1";
		int position=distance(v7.begin(),it4);
		cout<<" and the position of 1 is: "<<position+1<<endl;//remember to add 1 to position which caculated from distance
	}

/*modify更改*/
	//查找到删除再增加。。。

	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/m0_37561165/article/details/80968293
今日推荐