一、vector介绍
- vector是表示可变大小数组的序列容器。
- 就像数组一样,vector也采用的连续存储空间来存储元素。也就是意味着可以采用下标对vector的元素进行访问,和数组一样高效。但是又不像数组,它的大小是可以动态改变的,而且它的大小会被容器自动处理。
- 本质讲,vector使用动态分配数组来存储它的元素。当新元素插入时候,这个数组需要被重新分配大小为了增加存储空间。其做法是,分配一个新的数组,然后将全部元素移到这个数组。就时间而言,这是一个相对代价高的任务,因为每当一个新的元素加入到容器的时候,vector并不会每次都重新分配大
小。 - vector分配空间策略:vector会分配一些额外的空间以适应可能的增长,因为存储空间比实际需要的存储空间更大。不同的库采用不同的策略权衡空间的使用和重新分配。但是无论如何,重新分配都应该是对数增长的间隔大小,以至于在末尾插入一个元素的时候是在常数时间的复杂度完成的。
- 因此,vector占用了更多的存储空间,为了获得管理存储空间的能力,并且以一种有效的方式动态增长。
- 与其它动态序列容器相比(deques, lists and forward_lists) ,vector在访问元素的时候更加高效,在末尾添加和删除元素相对高效。对于其它不在末尾的删除和插入操作,效率更低。比起lists和forward_lists统一的迭代器和引用更好。
- vector: STL提供一个泛型的动态类型的顺序表,泛型:任意类型的元素都可以存储;顺序表:底层是一段连续空间;动态类型顺序表: vector会自动进行库容
二、vector接口说明
1、vector常见构造函数
#include <iostream>
#include <vector>
int main()
{
// constructors used in the same order as described above:
std::vector<int> first; // empty vector of ints
std::vector<int> second(4, 100); // four ints with value 100
std::vector<int> third(second.begin(), second.end()); // iterating through second
std::vector<int> fourth(third); // a copy of third
// 下面涉及迭代器初始化的部分,我们学习完迭代器再来看这部分
// the iterator constructor can also be used to construct from arrays:
int myints[] = {
16,2,77,29 };
std::vector<int> fifth(myints, myints + sizeof(myints) / sizeof(int));
std::cout << "The contents of fifth are:";
for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
2、vector iterator的使用
#include <iostream>