vector是标准模板库中我们经常使用的容器,它与数组类似,它拥有一段连续的内存空间,并且起始地址不变,因此它能很好的支持随机存取(使用[]操作符访问其中的元素).但由于它的内存空间是连续的,所以在中间进行插入和删除操作会造成内存块的拷贝(复杂度为O(n)),另外,当该数组的内存空间不够时,需要重新申请一块足够大的内存并进行内存的拷贝,这些都大大影响了vector的效率。每个编译器对它进行内存分配时,一般是当前大小的两倍,然后把原数组的内容拷贝过去。
下面是vector的简单使用:
#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
void vectorDemo();
int main()
{
vectorDemo();
system("PAUSE");
return 0;
}
//容器的使用
void vectorDemo()
{
const int SIZE = 6;
int array[SIZE] = { 1, 2, 3, 4, 5, 6 };
//声明一个int类型集合的容器,并用数组array对容器进行初始化
vector<int> v(array, array + SIZE);
cout << "Frist element:" << v.front() << "\nLast element:" << v.back() << endl; //1 6
//通过下标操作符和at函数来修改容器中的函数
//at函数会检查下标是否越界
v[1] = 7; //1 7 3 4 5 6
v.at(2) = 10; //1 7 10 4 5 6
//在第二个位置插入22元素
v.insert(v.begin() + 1, 22); //1 22 7 10 4 5 6
//尾部添加元素19
v.push_back(19); //1 22 7 10 4 5 6 19
//声明一个迭代器(必须vector<int>::iterator)
vector<int>::iterator iter = v.begin();
while (iter != v.end()){
cout << *iter<<" "; //解引用
iter++; //迭代器向后移动
}
cout << endl;
//查找元素22的位置,并返回迭代器
iter = find(v.begin(), v.end(), 22);
if (iter != v.end()){
cout << "Location:" << (iter - v.begin()) << endl;
}
else{
cout << "not found" << endl;
}
//系统的最大容量
cout << "The max size of the vector is:" << v.max_size()<<endl;
//容器的容量
cout << "The size of the vector is:" << v.size() << endl;;
//当前的最大容量
cout << "The current capacity is:" << v.capacity() << endl;
try{
v.at(10) = 88; //越界,抛异常
}
catch (out_of_range & e){
cout << "Exception:" << e.what() << endl;
}
//清除容器中的元素
v.erase(v.begin()); //清除第一个元素
v.erase(v.begin(), v.end()); //清除容器中的全部元素
cout << "After erase,v " << (v.empty() ? "is" : "is not") << " empty" << endl;
//从开始位置把数组插入容器中
v.insert(v.begin(), array, array + SIZE);
cout << "After erase,v " << (v.empty() ? "is" : "is not") << " empty" << endl;
//用clear函数清空容器
v.clear();
cout << "After erase,v " << (v.empty() ? "is" : "is not") << " empty" << endl;
}