vecotr基本概念

vecotr类似动态数组。其扩展机制是开辟新的更大的数组空间拷贝原来数组元素到新数组空间,并释放原空间

vector方法

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void printvector(vector <int> &v1)
{
	for (auto it = v1.begin(); it != v1.end(); it++)
		cout << *it << " ";
	cout << endl;
}
int main()
{
	vector <int> v1;
	for (size_t i = 0; i < 10; i++)
	{
		v1.push_back(i + 1);//尾插
	}
	if (v1.empty())
		cout << "v1为空" << endl;
	else{
		cout << "v1的容量为:" << v1.capacity() << endl;
		cout << "v1的大小为:" << v1.size() << endl;
	}
	printvector(v1);
	//v1.resize(20);
	//	v1.resize(20,0);补位指定为 0
	v1.pop_back();//删除最后一个元素
	printvector(v1);

	v1.insert(v1.begin(), -1);//指定位置插入
	printvector(v1);

	//v1.erase(v1.begin());//删第一个
	v1.erase(v1.begin() + 4, v1.end());//区间删除
	printvector(v1);

	vector <int> (v1).swap(v1);//交换容器的指针

	vector <int> v2;
	v2.reserve(100);//预留空间,数据量已知的情况下减少开辟空间次数
	if (v2.empty()){
		cout << "v2为空" << endl;
		cout << "v2的容量为:" << v2.capacity() << endl;
		cout << "v2的大小为:" << v2.size() << endl;
	}
	else{
		cout << "v2不为空" << endl;
		cout << "v2的容量为:" << v2.capacity() << endl;
		cout << "v2的大小为:" << v2.size() << endl;
	}

	system("pause");
	return 0;
}