【C++】STL顺序容器vector

顺序容器Vector

STL提供的vector相对于C++中提出的array而言,本质上是相同的,只不过C++的数组将数组空间大小的增加这一步骤交给了程序员来做,而STL将这一步骤完全封装好,交给了程序来做。

vector的内部存在三个迭代器来控制空间大小。
{
iterator start;          	//表示目前使用空间的头
iterator finish;			//表示目前使用空间的尾
iterator end_of_storage; 	//表示目前可用空间的尾
}

通过这三个位置指针来判断是否需要进行内存迁移。对于编程而言,需要注意一点的是,一旦发生了内存迁移,则以前所赋值的迭代器将失效。

#include<iostream>
#include <vector>
using namespace std;
int main()
{
	vector <int> arr(5, 0);
	/*定义一个迭代器指向第一个元素*/
	vector <int> ::iterator ite = arr.begin();
	cout << "capacity:  " << arr.capacity() << endl;  //capacity: 5
	arr.push_back(1);
	arr.push_back(2);
	arr.push_back(3);
	arr.push_back(4);	
	cout << "capacity:  " << arr.capacity() << endl;  //capacity: 10
	/*该迭代器已经失效,因为已经发生了内存搬移,会发生错误*/
	cout << *ite << endl;
	system("pause");
	return 0;
}

vector常用的API

API 功能
push_back 在数组的最后添加一个数据
pop_back 去掉数组的最后一个数据
at 得到编号位置的数据
begin 得到数组头的指针
end 得到数组的最后一个单元+1的指针
max_size 得到vector最大可以是多大
capacity 当前vector分配的大小
size 当前使用数据的大小
clear 清空当前的vector
rbegin 将vector反转后的开始指针返回(其实就是原来的end-1)
rend 将vector反转构的结束指针返回(其实就是原来的begin-1)
empty 判断vector是否为空
erase 删除指针指向的数据项

例子

1.定义

#include<iostream>
#include <vector>
using namespace std;
int main()
{
	vector <int> arr(5, 0);
	//vector <int> ::iterator ite = arr.begin();
	cout << "max size: " << arr.max_size() << "  capacity:" << arr.capacity() << endl;
	cout << "*************************************************" << endl;
	arr.push_back(1);
	arr.push_back(2);
	arr.push_back(3);
	arr.push_back(4);
	for (vector <int>::iterator it = arr.begin(); it != arr.end(); it++)
	{
		cout << "value: " << *it << "  size:" << arr.size() << "  capacity:" << arr.capacity() << endl;
		cout << "*************************************************" << endl;
	}

	cout << "end of data" << arr.back() << endl;
	cout << "begin of data:" << arr.front() << endl;
	cout << "*************************************************" << endl;
	arr.pop_back();
	arr.pop_back();
	cout << "max size: " << arr.max_size() << "capacity:" << arr.capacity() << endl;
	cout << "*************************************************" << endl;
	for (vector <int>::reverse_iterator it = arr.rbegin(); it != arr.rend(); it++)
	{
		cout << "value: " << *it << "  size:" << arr.size() << "  capacity:" << arr.capacity() << endl;
		cout << "*************************************************" << endl;
	}
	//cout << *ite << endl;
	system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/Raowz/p/14596038.html