vector

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;

void print(vector<int> v)
{
	for(vector<int>::iterator it=v.begin();it!=v.end();it++)
		cout<<*it<<"  ";
	cout<<endl;

}
//初始化
void test01()
{
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));          //1.两个迭代器
	//print(v1);
	vector<int>v2;                                          //2.初始化成空的
	print(v2); 
	vector<int>v3(20,1);                                     //3.初始化成n个x
	print(v3);
}
//插入
void test02()
{	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));    
	v1.insert(v1.begin()+3,100);                         //在pos前插入
	print(v1);
	v1.insert(v1.begin()+6,5,200);
	print(v1);											//在position前插入n 个元素
	v1.insert(v1.begin()+2,v1.begin ()+4,v1.begin()+8);    //insert(p,i,j)  将序列【i,j)中的元素插入p之前   
	print(v1);
}
//删除
void test03()
{	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	v1.erase(v1.begin()+2,v1.begin ()+4);
	print(v1);
	v1.erase (v1.begin());
	print(v1);               //删除迭代器指向的
}
//赋值
void test04()
{
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	vector<int>v2;
	v2=v1;
	print(v2);
}
//首尾
void test05()
{
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	cout<<"front: "<<v1.front()<<endl;
	cout<<"back: "<<v1.back()<<endl;
}
//size 判空
void test06()
{
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	if(v1.empty())
		cout<<"kong!";
	else
	cout<<v1.size()<<endl;
}
//清空  capacity
void test07()
{
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	v1.clear();
	print(v1);
	for(int i=1;i<=10000;i++)
		v1.push_back(i);
	cout<<"size: "<<v1.size()<<endl;
	cout<<"capacity: "<<v1.capacity()<<endl;
}
//resize
void test08()
{
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	print(v1);
	v1.resize(3);
	print(v1);
	v1.resize(8);
	print(v1);
	v1.resize(10,1);
	print(v1);
}
//swap 交换
void test09()
{
	
	int arr[]={1,5,6,5,5,6,2,8,9};
	vector<int>v1(arr,arr+sizeof(arr)/sizeof(int));
	int arr1[]={10,10,10,10,10,10};
	vector<int>v2(arr1,arr1+sizeof(arr1)/sizeof(int));
	print(v1);
	print(v2);
	v1.swap(v2);
	print(v1);
	print(v2);
}
int main()
{
	test01();
	//test02();
	//test03();
	/*test04();
	test05();
	test06();
	test07();
	test08();*/
	//test09();
	return 0;
}
posted @ 2020-02-20 11:58  DuJunlong  阅读(5)  评论(0编辑  收藏  举报  来源