vector是)C++中的一種數據結構,確切的說是一個類.它相當於一個動態的數組,當程序員無法知道自己需要的數組的規模多大時,用其來解決問題可以達到最大節約空間的目的
1、vectot與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()來刪除數據,
當刪除數據時,應該知道要刪除尾部的數據,或者是刪除所有數據,還是個別的數據。