1. 序列式容器
在C++中,容器大致分为2类。分别是序列式容器和关联式容器。其中,序列式容器有vector、list、deque以及C++11中的forward。序列式容器的底层是线性序列的数据结构,里面存储的是元素本身。例如:
vector<int> V;
2.vector
1、vector的模板参数列表
template < class T, class Alloc = allocator<T> >
class vector;
2、vector的构造
构造函数 | 返回值 |
---|
vector(); | 无参构造 | vector(size_type n, const value_type& val = value_type()) | 使用n个val初始化 | vector (const vector& x); (重点) | 拷贝构造 | vector (InputIterator first, InputIterator last); | 使用迭代器进行构造 |

3.vector的迭代器使用
iterator的使用 | 说明 |
---|
iterator begin();const_iterator begin() const; | 获取第一个数据位置的迭代器 | iterator end();const_iterator end() const; | 获取最后一个数据下一个位置的迭代器 | reverse_iterator rend();const_reverse_iterator rend() const; | | 反向迭代器 | |
  
3.vector中空间增长问题
函数 | 返回值 |
---|
size_type size() const; | 返回vector中元素的总个数,并不等于capacity | size_type capacity() const; | Return size of allocated storage capacity 返回的是申请空间的大小 (注意:This capacity is not necessarily equal to the vector size.) | bool empty() const; | 判断size是否等于0 | void resize (size_type n, value_type val = value_type()); | 开空间+初始化。(注意:这里需要分情况讨论,讨论n的值和size的大小。如果n<size,那么就减小到n,并移除多余的元素。n大于size,如果val有指定,那么就将大于的部分使用val进行填充。如果n>capacity,那么就会进行扩容) | void reserve (size_type n); | Request a change in capacity 改变的是capacity的值。 |

  4.vector中增删查改
函数 | 返回值 |
---|
void push_back (const value_type& val); | 在数组尾部进行插入 | void pop_back(); | 删除数据尾部的元素。并且会- -size | iterator insert (iterator position, const value_type& val); | 使用迭代器进行插入 | reference operator[] (size_type n);const_reference operator[] (size_type n) const; | Returns a reference to the element at position n in the vector container. |
 5.vector迭代器失效的问题
迭代器底层其实是指针。
迭代器失效分为两种情况:
(1)出现野指针:当insert时如果出现增容的情况,那么会释放原空间,
将原空间的内容拷贝到新空间中。从而导致出现野指针的问题。
(2)意义改变:erase删除之后,位置会向前移动一个。如果删除的是最后的元素,
那么可能对会指向end位置。
|