vector实现和使用
来源:互联网 发布:清真食品 知乎 编辑:程序博客网 时间:2024/06/16 22:07
1、vector与array
vector与array非常相似。两者的唯一区别在于空间的运用的灵活性。array是静态空间,一旦配置了就不能改变;vector是动态空间,随着元素的加入,它的内部机制会自行扩充空间以容纳新元素。因此,vector的运用对于内存的合理利用与运用的灵活性有很大的帮助,因此也不必因为害怕空间不足而一开始要求一个大块头的array了。另外,由于vector维护的是一个连续线性空间,所以vector支持随机存取。注意:vector动态增加大小时,并不是在原空间之后持续新空间(因为无法保证原空间之后尚有可供配置的空间),而是以原大小的两倍另外配置一块较大的空间,然后将原内容拷贝过来,然后才开始在原内容之后构造新元素,并释放原空间。因此,对vector的任何操作,一旦引起空间重新配置,指向原vector的所有迭代器就都失效了。这是程序员易犯的一个错误,务需小心。
2、vector原码分析
- class vector
- {
- public:
- // vector的嵌套类型定义,typedefs用于提供iterator_traits<I>支持
- typedef T value_type;
- typedef value_type* pointer;
- typedef value_type* iterator;
- typedef value_type& reference;
- typedef size_t size_type;
- typedef ptrdiff_t difference_type;
- protected:
- // 这个提供STL标准的allocator接口
- typedef simple_alloc <value_type, Alloc> data_allocator;
- iterator start; // 表示目前使用空间的头
- iterator finish; // 表示目前使用空间的尾
- iterator end_of_storage; // 表示实际分配内存空间的尾
- void insert_aux(iterator position, const T& x);
- // 释放分配的内存空间
- void deallocate()
- {
- // 由于使用的是data_allocator进行内存空间的分配,
- // 所以需要同样使用data_allocator::deallocate()进行释放
- // 如果直接释放, 对于data_allocator内部使用内存池的版本
- // 就会发生错误
- if (start)
- data_allocator::deallocate(start, end_of_storage - start);
- }
- void fill_initialize(size_type n, const T& value)
- {
- start = allocate_and_fill(n, value);
- finish = start + n; // 设置当前使用内存空间的结束点
- // 构造阶段, 此实作不多分配内存,
- // 所以要设置内存空间结束点和, 已经使用的内存空间结束点相同
- end_of_storage = finish;
- }
- public:
- // 获取几种迭代器
- iterator begin() { return start; }
- iterator end() { return finish; }
- // 返回当前对象个数
- size_type size() const { return size_type(end() - begin()); }
- size_type max_size() const { return size_type(-1) / sizeof(T); }
- // 返回重新分配内存前最多能存储的对象个数
- size_type capacity() const { return size_type(end_of_storage - begin()); }
- bool empty() const { return begin() == end(); }
- reference operator[](size_type n) { return *(begin() + n); }
- // 本实作中默认构造出的vector不分配内存空间
- vector() : start(0), finish(0), end_of_storage(0) {}
- vector(size_type n, const T& value) { fill_initialize(n, value); }
- vector(int n, const T& value) { fill_initialize(n, value); }
- vector(long n, const T& value) { fill_initialize(n, value); }
- // 需要对象提供默认构造函数
- explicit vector(size_type n) { fill_initialize(n, T()); }
- vector(const vector<T, Alloc>& x)
- {
- start = allocate_and_copy(x.end() - x.begin(), x.begin(), x.end());
- finish = start + (x.end() - x.begin());
- end_of_storage = finish;
- }
- ~vector()
- {
- // 析构对象
- destroy(start, finish);
- // 释放内存
- deallocate();
- }
- vector<T, Alloc>& operator=(const vector<T, Alloc>& x);
- // 提供访问函数
- reference front() { return *begin(); }
- reference back() { return *(end() - 1); }
- ////////////////////////////////////////////////////////////////////////////////
- // 向容器尾追加一个元素, 可能导致内存重新分配
- ////////////////////////////////////////////////////////////////////////////////
- // push_back(const T& x)
- // |
- // |---------------- 容量已满?
- // |
- // ----------------------------
- // No | | Yes
- // | |
- // ↓ ↓
- // construct(finish, x); insert_aux(end(), x);
- // ++finish; |
- // |------ 内存不足, 重新分配
- // | 大小为原来的2倍
- // new_finish = data_allocator::allocate(len); <stl_alloc.h>
- // uninitialized_copy(start, position, new_start); <stl_uninitialized.h>
- // construct(new_finish, x); <stl_construct.h>
- // ++new_finish;
- // uninitialized_copy(position, finish, new_finish); <stl_uninitialized.h>
- ////////////////////////////////////////////////////////////////////////////////
- void push_back(const T& x)
- {
- // 内存满足条件则直接追加元素, 否则需要重新分配内存空间
- if (finish != end_of_storage)
- {
- construct(finish, x);
- ++finish;
- }
- else
- insert_aux(end(), x);
- }
- ////////////////////////////////////////////////////////////////////////////////
- // 在指定位置插入元素
- ////////////////////////////////////////////////////////////////////////////////
- // insert(iterator position, const T& x)
- // |
- // |------------ 容量是否足够 && 是否是end()?
- // |
- // -------------------------------------------
- // No | | Yes
- // | |
- // ↓ ↓
- // insert_aux(position, x); construct(finish, x);
- // | ++finish;
- // |-------- 容量是否够用?
- // |
- // --------------------------------------------------
- // Yes | | No
- // | |
- // ↓ |
- // construct(finish, *(finish - 1)); |
- // ++finish; |
- // T x_copy = x; |
- // copy_backward(position, finish - 2, finish - 1); |
- // *position = x_copy; |
- // ↓
- // data_allocator::allocate(len); <stl_alloc.h>
- // uninitialized_copy(start, position, new_start); <stl_uninitialized.h>
- // construct(new_finish, x); <stl_construct.h>
- // ++new_finish;
- // uninitialized_copy(position, finish, new_finish); <stl_uninitialized.h>
- // destroy(begin(), end()); <stl_construct.h>
- // deallocate();
- ////////////////////////////////////////////////////////////////////////////////
- iterator insert(iterator position, const T& x)
- {
- size_type n = position - begin();
- if (finish != end_of_storage && position == end())
- {
- construct(finish, x);
- ++finish;
- }
- else
- insert_aux(position, x);
- return begin() + n;
- }
- iterator insert(iterator position) { return insert(position, T()); }
- void pop_back()
- {
- --finish;
- destroy(finish);
- }
- iterator erase(iterator position)
- {
- if (position + 1 != end())
- copy(position + 1, finish, position);
- --finish;
- destroy(finish);
- return position;
- }
- iterator erase(iterator first, iterator last)
- {
- iterator i = copy(last, finish, first);
- // 析构掉需要析构的元素
- destroy(i, finish);
- finish = finish - (last - first);
- return first;
- }
- // 调整size, 但是并不会重新分配内存空间
- void resize(size_type new_size, const T& x)
- {
- if (new_size < size())
- erase(begin() + new_size, end());
- else
- insert(end(), new_size - size(), x);
- }
- void resize(size_type new_size) { resize(new_size, T()); }
- void clear() { erase(begin(), end()); }
- protected:
- // 分配空间, 并且复制对象到分配的空间处
- iterator allocate_and_fill(size_type n, const T& x)
- {
- iterator result = data_allocator::allocate(n);
- uninitialized_fill_n(result, n, x);
- return result;
- }
- // 提供插入操作
- ////////////////////////////////////////////////////////////////////////////////
- // insert_aux(iterator position, const T& x)
- // |
- // |---------------- 容量是否足够?
- // ↓
- // -----------------------------------------
- // Yes | | No
- // | |
- // ↓ |
- // 从opsition开始, 整体向后移动一个位置 |
- // construct(finish, *(finish - 1)); |
- // ++finish; |
- // T x_copy = x; |
- // copy_backward(position, finish - 2, finish - 1); |
- // *position = x_copy; |
- // ↓
- // data_allocator::allocate(len);
- // uninitialized_copy(start, position, new_start);
- // construct(new_finish, x);
- // ++new_finish;
- // uninitialized_copy(position, finish, new_finish);
- // destroy(begin(), end());
- // deallocate();
- ////////////////////////////////////////////////////////////////////////////////
- template <class T, class Alloc>
- void insert_aux(iterator position, const T& x)
- {
- if (finish != end_of_storage) // 还有备用空间
- {
- // 在备用空间起始处构造一个元素,并以vector最后一个元素值为其初值
- construct(finish, *(finish - 1));
- ++finish;
- T x_copy = x;
- copy_backward(position, finish - 2, finish - 1);
- *position = x_copy;
- }
- else // 已无备用空间
- {
- const size_type old_size = size();
- const size_type len = old_size != 0 ? 2 * old_size : 1;
- // 以上配置元素:如果大小为0,则配置1(个元素大小)
- // 如果大小不为0,则配置原来大小的两倍
- // 前半段用来放置原数据,后半段准备用来放置新数据
- iterator new_start = data_allocator::allocate(len); // 实际配置
- iterator new_finish = new_start;
- // 将内存重新配置
- try
- {
- // 将原vector的安插点以前的内容拷贝到新vector
- new_finish = uninitialized_copy(start, position, new_start);
- // 为新元素设定初值 x
- construct(new_finish, x);
- // 调整水位
- ++new_finish;
- // 将安插点以后的原内容也拷贝过来
- new_finish = uninitialized_copy(position, finish, new_finish);
- }
- catch(...)
- {
- // 回滚操作
- destroy(new_start, new_finish);
- data_allocator::deallocate(new_start, len);
- throw;
- }
- // 析构并释放原vector
- destroy(begin(), end());
- deallocate();
- // 调整迭代器,指向新vector
- start = new_start;
- finish = new_finish;
- end_of_storage = new_start + len;
- }
- }
- ////////////////////////////////////////////////////////////////////////////////
- // 在指定位置插入n个元素
- ////////////////////////////////////////////////////////////////////////////////
- // insert(iterator position, size_type n, const T& x)
- // |
- // |---------------- 插入元素个数是否为0?
- // ↓
- // -----------------------------------------
- // No | | Yes
- // | |
- // | ↓
- // | return;
- // |----------- 内存是否足够?
- // |
- // -------------------------------------------------
- // Yes | | No
- // | |
- // |------ (finish - position) > n? |
- // | 分别调整指针 |
- // ↓ |
- // ---------------------------- |
- // No | | Yes |
- // | | |
- // ↓ ↓ |
- // 插入操作, 调整指针 插入操作, 调整指针 |
- // ↓
- // data_allocator::allocate(len);
- // new_finish = uninitialized_copy(start, position, new_start);
- // new_finish = uninitialized_fill_n(new_finish, n, x);
- // new_finish = uninitialized_copy(position, finish, new_finish);
- // destroy(start, finish);
- // deallocate();
- ////////////////////////////////////////////////////////////////////////////////
- template <class T, class Alloc>
- void insert(iterator position, size_type n, const T& x)
- {
- // 如果n为0则不进行任何操作
- if (n != 0)
- {
- if (size_type(end_of_storage - finish) >= n)
- { // 剩下的备用空间大于等于“新增元素的个数”
- T x_copy = x;
- // 以下计算插入点之后的现有元素个数
- const size_type elems_after = finish - position;
- iterator old_finish = finish;
- if (elems_after > n)
- {
- // 插入点之后的现有元素个数 大于 新增元素个数
- uninitialized_copy(finish - n, finish, finish);
- finish += n; // 将vector 尾端标记后移
- copy_backward(position, old_finish - n, old_finish);
- fill(position, position + n, x_copy); // 从插入点开始填入新值
- }
- else
- {
- // 插入点之后的现有元素个数 小于等于 新增元素个数
- uninitialized_fill_n(finish, n - elems_after, x_copy);
- finish += n - elems_after;
- uninitialized_copy(position, old_finish, finish);
- finish += elems_after;
- fill(position, old_finish, x_copy);
- }
- }
- else
- { // 剩下的备用空间小于“新增元素个数”(那就必须配置额外的内存)
- // 首先决定新长度:就长度的两倍 , 或旧长度+新增元素个数
- const size_type old_size = size();
- const size_type len = old_size + max(old_size, n);
- // 以下配置新的vector空间
- iterator new_start = data_allocator::allocate(len);
- iterator new_finish = new_start;
- __STL_TRY
- {
- // 以下首先将旧的vector的插入点之前的元素复制到新空间
- new_finish = uninitialized_copy(start, position, new_start);
- // 以下再将新增元素(初值皆为n)填入新空间
- new_finish = uninitialized_fill_n(new_finish, n, x);
- // 以下再将旧vector的插入点之后的元素复制到新空间
- new_finish = uninitialized_copy(position, finish, new_finish);
- }
- # ifdef __STL_USE_EXCEPTIONS
- catch(...)
- {
- destroy(new_start, new_finish);
- data_allocator::deallocate(new_start, len);
- throw;
- }
- # endif /* __STL_USE_EXCEPTIONS */
- destroy(start, finish);
- deallocate();
- start = new_start;
- finish = new_finish;
- end_of_storage = new_start + len;
- }
- }
- }
- };
3、使用vector
(1)文件包含:
首先在程序开头处加上#include<vector>以包含所需要的类文件vector同时加上using namespace std;
(2)vector声明:
使用vector声明数组时,对于一维的数组,格式如右::vector <int> a;(等于声明了一个int数组a[],大小没有指定,可以动态的向里面添加删除);对于多维数组,可以直接给数组名加*,例如用vector代替二维数组.其实只要声明一个一维数组向量即可,而一个数组的名字其实代表的是它的首地址,所以只要声明一个地址的向量即可,即:vector <int *> a.同理想用向量代替三维数组也是一样,vector <int**>a;再往上面依此类推;
(3)成员函数作用
1.push_back 在数组的最后添加一个数据
2.pop_back 去掉数组的最后一个数据
3.at 得到编号位置的数据
4.begin 得到数组头的指针
5.end 得到数组的最后一个单元+1的指针
6.front 得到数组头的引用
7.back 得到数组的最后一个单元的引用
8.max_size 得到vector最大可以是多大
9.capacity 当前vector分配的大小
10.size 当前使用数据的大小
11.resize 改变当前使用数据的大小,如果它比当前使用的大,者填充默认值
12.reserve 改变当前vecotr所分配空间的大小
13.erase 删除指针指向的数据项
14.clear 清空当前的vector
15.rbegin 将vector反转后的开始指针返回(其实就是原来的end-1)
16.rend 将vector反转构的结束指针返回(其实就是原来的begin-1)
17.empty 判断vector是否为空
18.swap 与另一个vector交换数据
(4)vector的用法实例
vector容器提供了多种创建方法,下面介绍几种常用的。
创建一个Widget类型的空的vector对象:
vector<Widget> vWidgets;
创建一个包含500个Widget类型数据的vector:
vector<Widget> vWidgets(500);
创建一个包含500个Widget类型数据的vector,并且都初始化为0:
vector<Widget> vWidgets(500, Widget(0));
向vector添加一个数据
vector添加数据的缺省方法是push_back()。
push_back()函数表示将数据添加到vector的尾部,并按需要来分配内存。
例如:向vector<Widget>中添加10个数据,需要如下编写代码:
for(int i= 0;i<10; i++) {
vWidgets.push_back(Widget(i));
}
获取vector中指定位置的数据
如果想知道vector是否存放了数据,可以使用empty()。
获取vector的大小,可以使用size()。
例如,如果想获取一个vector v的大小,但不知道它是否为空,或者是否已经包含了数据,如果为空想设置为-1,
你可以使用下面的代码实现:
int nSize = v.empty() ? -1 : v.size();
访问vector中的数据可以使用 vector::at()
at()进行了边界检查,如果访问超过了vector的范围,将抛出一个例外。
分析下面的代码:
vector<int> v;
v.reserve(10);
for(int i=0; i<7; i++) {
v.push_back(i);
}
try {
int iVal1 = v[7];
// not bounds checked - will not throw
int iVal2 = v.at(7);
// bounds checked - will throw if out of range
}
catch(const exception& e) {
cout << e.what();
}
删除vector中的数据
vector能够非常容易地添加数据,也能很方便地取出数据,
同样vector提供了erase(),pop_back(),clear()来删除数据,
当删除数据时,应该知道要删除尾部的数据,或者是删除所有数据,还是个别的数据。
- vector实现和使用
- 使用C++实现Vector
- 使用new和vector实现一维和二维数组
- 使用vector类实现string的输入和输出
- C++ vector实现关键点和使用注意事项
- STL库中的vector的使用和模拟实现
- (C++)vector & list 的使用和模拟实现
- vector和list的使用及其模拟实现
- 使用Vector实现二维数组
- Vector实现同步以及使用
- 使用vector实现优先队列
- 使用Vector实现二维数组
- 使用Vector实现二维数组
- ArrayList和Vector实现类
- ArrayList和Vector实现类
- Vector和Hashtable的使用:
- vector和bitset使用例子
- map和vector嵌套使用
- OpenCV提取显示一张图片的R,G,B颜色分量
- Java设计模式——命令模式、模板方法、迭代器和组合模式
- 12.07学习计划
- Linux中c程序的编译链接过程2017/12/10
- cef3编译记录经典资料
- vector实现和使用
- java--数组3
- UE4 道路编辑 Spline的使用
- 导致微信公众平台设置网页授权域名“无法访问xxx指向的web服务器(或虚拟主机)的目录,请检查网络设置”的一种原因
- 项目日记3—服务器环境搭建(二)
- 蓝桥杯 算法训练 6-1 递归求二项式系数值
- Python(2)————变量的6大标准数据类型
- AttributeError: '_Screen' object has no attribute 'onkeypress' python 的例子
- Redis客户端之jedis的使用简介