C++超詳細(xì)講解模擬實(shí)現(xiàn)vector
1. 模擬實(shí)現(xiàn)vector
我們模擬實(shí)現(xiàn)是為了加深對(duì)這個(gè)容器的理解,不是為了造更好的輪子。
快速搭一個(gè)vector的架子
// vector.h #pragma once #include <assert.h> // 模擬實(shí)現(xiàn) -- 加深對(duì)這個(gè)容器理解,不是為了造更好的輪子 namespace Yuucho { template<class T> class vector { public: typedef T* iterator; typedef const T* const_iterator; vector() :_start(nullptr) , _finish(nullptr) , _endofstorage(nullptr) {} // 迭代器區(qū)間來(lái)構(gòu)造,用模板的原因是存儲(chǔ)的類(lèi)型多種多樣 template <class InputIterator> vector(InputIterator first, InputIterator last) : _start(nullptr) , _finish(nullptr) , _endofstorage(nullptr) { while (first != last) { push_back(*first); ++first; } } // 用n個(gè)T去構(gòu)造,但是會(huì)隱藏匹配問(wèn)題 vector(size_t n, const T& val = T()) : _start(nullptr) , _finish(nullptr) , _endofstorage(nullptr) { reserve(n); for (size_t i = 0; i < n; ++i) { push_back(val); } } void swap(vector<T>& v) { std::swap(_start, v._start); std::swap(_finish, v._finish); std::swap(_endofstorage, v._endofstorage); } //拷貝構(gòu)造函數(shù) vector(const vector<T>& v) : _start(nullptr) , _finish(nullptr) , _endofstorage(nullptr) { vector<T> tmp(v.begin(), v.end()); swap(tmp); } // 拷貝賦值函數(shù) vector<T>& operator=(vector<T> v) { swap(v); return *this; } // 資源管理 ~vector() { if(_start) { delete[] _start; _start = _finish = _endofstorage = nullptr; } } iterator begin() { return _start; } iterator end() { return _finish; } const_iterator begin() const { return _start; } const_iterator end() const { return _finish; } // 默認(rèn)是內(nèi)聯(lián),頻繁調(diào)用不用擔(dān)心棧幀消耗 size_t size() const { return _finish - _start; } size_t capacity() const { return _endofstorage - _start; } void reserve(size_t n) { } //void resize(size_t n, const T& val = T()) void resize(size_t n, T val = T()) { } void push_back(const T& x) { } void pop_back() { } T& operator[](size_t pos) { assert(pos < size()); return _start[pos]; } const T& operator[](size_t pos) const { assert(pos < size()); return _start[pos]; } iterator insert(iterator pos, const T& x) { } void clear() { _finish = _start; } private: iterator _start; iterator _finish; iterator _endofstorage; }; }
2. vector常用接口
2.1 reserve
跟string的擴(kuò)容思路一樣。一般不考慮縮容(n<capacity),因?yàn)檫@是時(shí)間換空間的做法,我們要的是效率。
錯(cuò)誤代碼:
void reserve(size_t n) { // 一般不考慮縮容(n<capacity) if(n > capacity()) { T* tmp = new T[n]; // capacity為0,n就是4(_endofstorage、_start都為nuptr) // 有數(shù)據(jù)才拷貝 if(_start) { memcpy(tmp, _start, size()*sizeof(T)); delete[] _start; } _start = tmp; // 注意,這里start位置變了 } // 更新_finish、_endofstorage _finish = _start + size(); // size():_finish - _start, _finish還是空指針 _endofstorage = _start + capacity; //capacity起始為0,也不對(duì) }
修正后的代碼:
void reserve(size_t n) { // 記錄size size_t sz = size(); if(n > capacity()) { T* tmp = new T[n]; if(_start) { //memcpy還會(huì)隱藏更深層次的深淺拷貝問(wèn)題,講解在最后 memcpy(tmp, _start, size()*sizeof(T)); delete[] _start; } _start = tmp; // 注意,這里start位置變了 } // 更新_finish、_endofstorage _finish = _start + sz; _endofstorage = _start + n; }
2.2 resize
resize是開(kāi)空間+初始化,size_type就是size_t,value_type就是T。
C++模板出來(lái)了語(yǔ)法就必須支持內(nèi)置類(lèi)型的默認(rèn)構(gòu)造、析構(gòu)函數(shù)。
int() // 默認(rèn)構(gòu)造是0
double() // 默認(rèn)構(gòu)造是0.0
int*() // 默認(rèn)構(gòu)造是nullptr
思路與string一樣
//void resize(size_t n, const T& val = T()) 嚴(yán)格的編譯器編不過(guò),它認(rèn)為T(mén)是臨時(shí)對(duì)象 // 按照庫(kù)里的寫(xiě)法 void resize(size_t n, T val = T()) // T類(lèi)型的匿名對(duì)象,默認(rèn)構(gòu)造函數(shù)很重要,內(nèi)置類(lèi)型咋辦? { if (n > capacity()) { reserve(n); } if (n > size()) { while (_finish < _start + n) { *_finish = val; ++_finish; } } // n < capacity就是刪除數(shù)據(jù) else { _finish = _start + n; } }
2.3 push_back
void push_back(const T& x) { // 滿(mǎn)了先擴(kuò)容 if(_finish == _endofstorage) { size_t newCapacity = capacity() == 0 ? 4 : capacity() * 2; reserve(newCapacity); } // 插入數(shù)據(jù) *_finish = x; ++_finish; }
復(fù)用insert:
void push_back(const T& x) { insert(end(), x); }
2.4 pop_back()
void pop_back() { // 如果不為空 if(_finish > _start) { --_finish; } }
復(fù)用erase:
void pop_back() { erase(end()-1); }
2.5 insert
庫(kù)里面的insert是帶返回值的,我們先不管,先寫(xiě)一個(gè)沒(méi)有返回值的看看。
void insert(iterator pos, const T& x) { // 檢查參數(shù) assert(pos >= _start && pos <= _finish); // 擴(kuò)容 if (_finish == _endofstorage) { size_t newCapacity = capacity() == 0 ? 4 : capacity() * 2; reserve(newCapacity); } // 挪動(dòng)數(shù)據(jù) iterator end = _finish - 1; while (end >= pos) { *(end + 1) = *end; --end; } *pos = x; ++_finish; }
(1) 迭代器失效第一種場(chǎng)景
yeahbaby,現(xiàn)在我們就可以來(lái)講講迭代器失效的問(wèn)題了,嘿嘿嘿。
如果插入時(shí)沒(méi)有擴(kuò)容,ok,那還好說(shuō),沒(méi)有問(wèn)題。
如果擴(kuò)容了,reserve會(huì)去更新_start
和_finish
,而不會(huì)去更新pos(pos還是會(huì)指向舊空間,迭代器發(fā)生了野指針問(wèn)題)。在VS環(huán)境下,會(huì)用斷言暴力檢查出來(lái)的。在Linux環(huán)境下,檢查不出來(lái)這種情況,甚至對(duì)原來(lái)的it仍然可讀可寫(xiě)。
ok,那我們?cè)跀U(kuò)容時(shí)更新一下pos:
if (_finish == _endofstorage) { size_t n = pos - _start; size_t newCapacity = capacity() == 0 ? 4 : capacity() * 2; reserve(newCapacity); pos = _start + n; }
(2)另一種場(chǎng)景
void test_vector1() { // 在所有的偶數(shù)的前面插入2 vector<int> v; //v.reserve(10); v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); v.push_back(6); vector<int>::iterator it = v.begin(); while (it != v.end()) { if (*it % 2 == 0) { it = v.insert(it, 20); ++it; } ++it; } for (auto e : v) { cout << e << " "; } cout << endl; } }
運(yùn)行結(jié)果
導(dǎo)致斷言錯(cuò)誤的原因是啥?為什么不能在2的前面插入20?
同樣的道理,雖然我們修正了pos,但是我們是值傳遞,形參不會(huì)改變實(shí)參。所以it仍然是野指針。在VS環(huán)境下,會(huì)用斷言暴力檢查出來(lái)的。在Linux環(huán)境下,檢查不出來(lái)這種情況,甚至對(duì)原來(lái)的it仍然可讀可寫(xiě)。
有小伙伴就會(huì)說(shuō)了,傳引用不就行了嗎?
我們是不會(huì)用引用的,官方庫(kù)也沒(méi)有用引用。因?yàn)槲乙獋鞯氖窍?code>v.begin()這樣的臨時(shí)對(duì)象怎么辦。
更悲傷的是就算我提前把空間給你開(kāi)好,保證插入時(shí)不需要擴(kuò)容還是會(huì)出現(xiàn)問(wèn)題。因?yàn)閕nsert是在2之前插入20,++it后it仍指向2,這樣就導(dǎo)致不斷地在2之前插入20。這也是迭代器失效的一種場(chǎng)景。
修正后的代碼:
用返回值解決,官方庫(kù)里返回的是指向新插入的第一個(gè)元素的迭代器。 那我們也這樣返回。
iterator insert(iterator pos, const T& x) { // 檢查參數(shù) assert(pos >= _start && pos <= _finish); // 擴(kuò)容 // 擴(kuò)容以后pos就失效了,需要更新一下 if (_finish == _endofstorage) { size_t n = pos - _start; size_t newCapacity = capacity() == 0 ? 4 : capacity() * 2; reserve(newCapacity); pos = _start + n; } // 挪動(dòng)數(shù)據(jù) iterator end = _finish - 1; while (end >= pos) { *(end + 1) = *end; --end; } *pos = x; ++_finish; return pos; }
此時(shí)我們這樣使用就行:
while (it != v.end()) { if(*it % 2 == 0) { // 返回新插入的第一個(gè)元素的迭代器 it = v.insert(it, 20); //還是指向2 ++it; } // 指向2的后一位 ++it; }
運(yùn)行結(jié)果
2.6 erase
一般vector刪除數(shù)據(jù),都不考慮縮容的方案。
縮容方案:size() < capacity()/2時(shí),可以考慮開(kāi)一個(gè)size()大小的空間,拷貝數(shù)據(jù),釋放舊空間。
縮容方案本質(zhì)是時(shí)間換空間。一般設(shè)計(jì)都不會(huì)考慮縮容,因?yàn)閷?shí)際比較關(guān)注時(shí)間效率,不關(guān)注空間效率,因?yàn)楝F(xiàn)在硬件設(shè)備空間都比較大,空間存儲(chǔ)也比較便宜。
我們這里不考慮縮容方案。
erase返回最后一個(gè)被釋放元素的后一個(gè)元素的新位置。
iterator erase(iterator pos) { assert(pos >= _start && pos < _finish); iterator it = pos + 1; while (it != _finish) { *(it - 1) = *it; ++it; } //erase最后一個(gè)數(shù)據(jù),則pos==_finish,pos真失效了,但仍然屬于這個(gè)容器 --_finish; return pos; }
VS中的vector也沒(méi)有考慮縮容方案,但是它對(duì)pos(如果縮容,pos就是野指針)進(jìn)行了斷言檢查,不允許訪(fǎng)問(wèn)和寫(xiě)入。
(1)erase迭代器的失效都是意義變了,或者不在有效訪(fǎng)問(wèn)數(shù)據(jù)的范圍。
(2)一般不會(huì)使用縮容的方案,那么erase的失效,一般也不存在野指針的失效。
erase(pos)以后pos失效了,pos的意義變了,但是不同平臺(tái)下面對(duì)訪(fǎng)問(wèn)pos的反應(yīng)不一樣。VS會(huì)強(qiáng)制檢查,Linux則沒(méi)有嚴(yán)格的檢查機(jī)制。我們用的時(shí)候一定要小心,統(tǒng)一以失效角度去看待。
erase迭代器意義變了的場(chǎng)景(假設(shè)我們要?jiǎng)h除容器中的偶數(shù)):
2.7 構(gòu)造函數(shù)的匹配問(wèn)題
迭代器區(qū)間的構(gòu)造函數(shù)的參數(shù)要求是同類(lèi)型的,而第一個(gè)構(gòu)造函數(shù)的第一個(gè)參數(shù)是size_t,int會(huì)涉及隱式類(lèi)型轉(zhuǎn)換。所以參數(shù)為(10,2)的會(huì)匹配迭代器區(qū)間的構(gòu)造函數(shù),而參數(shù)為(10, ‘x’)的會(huì)匹配第一個(gè)構(gòu)造函數(shù)。
這里就會(huì)導(dǎo)致int類(lèi)型被當(dāng)作迭代器解引用,本質(zhì)上是發(fā)生了構(gòu)造函數(shù)的錯(cuò)配問(wèn)題。
解決方法:
源碼是通過(guò)再寫(xiě)一個(gè)第一個(gè)參數(shù)為int類(lèi)型的構(gòu)造函數(shù)來(lái)解決的。
vector(int n, const T& val = T()) : _start(nullptr) , _finish(nullptr) , _endofstoage(nullptr) { reserve(n); for (int i = 0; i < n; ++i) { push_back(val); } }
3. 更深層次的深淺拷貝問(wèn)題
以楊輝三角為例:
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> vv; // 先開(kāi)辟楊輝三角的空間 vv.resize(numRows); //初始化每一行 for(size_t i = 0; i < numRows; ++i) { //每行個(gè)數(shù)依次遞增 vv[i].resize(i+1, 0); // 每一行的第一個(gè)和最后一個(gè)都是1 vv[i][0] = 1; vv[i][vv[i].size()-1] = 1; } for(size_t i = 0; i < vv.size(); ++i) { for(size_t j = 0; j < vv[i].size(); ++j) { if(vv[i][j] == 0) { //之間位置等于上一行j-1和j個(gè)相加 vv[i][j] = vv[i-1][j-1] + vv[i-1][j]; } } } return vv; } };
我們自己寫(xiě)的vector去跑這里的楊輝三角會(huì)出現(xiàn)問(wèn)題。
void test_vector2() { vector<vector<int>> ret = Solution().generate(5); for (size_t i = 0; i < ret.size(); ++i) { for (size_t j = 0; j < ret[i].size(); ++j) { cout << ret[i][j] << " "; } cout << endl; } cout << endl; }
為了方便大家理解,我們把擴(kuò)容的代碼拿下來(lái)。
void reserve(size_t n) { // 記錄size size_t sz = size(); if(n > capacity()) { T* tmp = new T[n]; if(_start) { memcpy(tmp, _start, size()*sizeof(T)); delete[] _start; } _start = tmp; // 注意,這里start位置變了 } // 更新_finish、_endofstorage _finish = _start + sz; _endofstorage = _start + n; }
vector<vector<int>> ret = Solution().generate(5);
會(huì)去調(diào)用拷貝構(gòu)造,拷貝構(gòu)造又去調(diào)用了迭代器的區(qū)間構(gòu)造函數(shù),迭代器區(qū)間構(gòu)造函數(shù)又去調(diào)用了push_back,push_back又去調(diào)用了reserve。
因?yàn)閜ush_back我們第一次開(kāi)的空間是4,所以前4次的push_back都不會(huì)有問(wèn)題,第5次push_back去調(diào)用reserve時(shí)就會(huì)出現(xiàn)問(wèn)題。
因?yàn)閿U(kuò)容的時(shí)候tmp會(huì)把前4組的vector<int>
數(shù)據(jù)memcpy下來(lái),而memcpy是淺拷貝,拷貝下來(lái)的數(shù)據(jù)和原來(lái)的數(shù)據(jù)指向的是同一塊空間。關(guān)鍵是memcpy后又delete了舊空間,導(dǎo)致插入第5個(gè)vector<int>
時(shí)前4組的數(shù)據(jù)被釋放了,成了野指針。
解決方法:
拷貝的時(shí)候不要用memcpy,使用拷貝賦值函數(shù)來(lái)完成,因?yàn)橘x值函數(shù)會(huì)幫我們完成深拷貝。
void reserve(size_t n) { // 記錄size size_t sz = size(); if(n > capacity()) { T* tmp = new T[n]; if(_start) { //防止淺拷貝問(wèn)題3 for (size_t i = 0; i < size(); ++i) { tmp[i] = _start[i]; } delete[] _start; } _start = tmp; // 注意,這里start位置變了 } // 更新_finish、_endofstorage _finish = _start + sz; _endofstorage = _start + n; }
到此這篇關(guān)于C++超詳細(xì)講解模擬實(shí)現(xiàn)vector的文章就介紹到這了,更多相關(guān)C++ vector內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語(yǔ)言實(shí)現(xiàn)查看進(jìn)程是否存在的方法示例
這篇文章主要介紹了C語(yǔ)言實(shí)現(xiàn)查看進(jìn)程是否存在的方法,涉及C語(yǔ)言針對(duì)進(jìn)程操作的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-07-07C語(yǔ)言數(shù)據(jù)結(jié)構(gòu)二叉樹(shù)簡(jiǎn)單應(yīng)用
這篇文章主要介紹了C語(yǔ)言數(shù)據(jù)結(jié)構(gòu)二叉樹(shù)簡(jiǎn)單應(yīng)用的相關(guān)資料,需要的朋友可以參考下2017-05-05C++實(shí)現(xiàn)哈夫曼樹(shù)簡(jiǎn)單創(chuàng)建與遍歷的方法
這篇文章主要介紹了C++實(shí)現(xiàn)哈夫曼樹(shù)簡(jiǎn)單創(chuàng)建與遍歷的方法,對(duì)于C++算法的學(xué)習(xí)來(lái)說(shuō)不失為一個(gè)很好的借鑒實(shí)例,需要的朋友可以參考下2014-07-07C++實(shí)現(xiàn)String與UF8互轉(zhuǎn)
這篇文章介紹了C++實(shí)現(xiàn)String與UF8互轉(zhuǎn)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05Android App仿微信界面切換時(shí)Tab圖標(biāo)變色效果的制作方法
這篇文章主要介紹了Android App仿微信界面切換時(shí)Tab圖標(biāo)變色效果的制作方法,重點(diǎn)講解了圖標(biāo)的繪制技巧,需要的朋友可以參考下2016-04-04