360搜索建站公司免費(fèi)發(fā)布推廣的網(wǎng)站有哪些
list
- 一、list-簡(jiǎn)單介紹
- 二、list的常用接口
- 1.常見構(gòu)造
- 2.iterator的使用
- 3.Capacity和Element access
- 4.Modifiers
- 5.list的迭代器失效
- 三、list實(shí)現(xiàn)
- 四、vector 和 list 對(duì)比
- 五、迭代器
- 1.迭代器的實(shí)現(xiàn)
- 2.迭代器的分類(按照功能分類)
- 3.反向迭代器
- (1)、包裝邏輯
- (2)、代碼
- 注意
一、list-簡(jiǎn)單介紹
list是一個(gè)可以在常熟范圍內(nèi)任意位置進(jìn)行插入和刪除的序列式容器。底層是帶頭雙向循環(huán)鏈表(鏈接中有對(duì)帶頭雙向循環(huán)鏈表的邏輯分析)。
二、list的常用接口
1.常見構(gòu)造
(constructor)構(gòu)造函數(shù)聲明 | 接口說明 |
---|---|
list() | 無參構(gòu)造 |
list(size_type n, const T& val = T() | 構(gòu)造并初始化n個(gè)val |
list(const list& x) | 拷貝構(gòu)造 |
list(InputIterator first, InputIterator last) | 使用迭代器[first, last)區(qū)間中的元素初始化構(gòu)造list |
test:
void test_constructor()
{list<int> lt1; //無參構(gòu)造list<int> lt2(4, 25); //構(gòu)造并初始化n個(gè)vallist<int> lt3(l2.begin(), l2.end()); //用lt2的[first, last)區(qū)間構(gòu)造list<int> lt4(l3); //拷貝構(gòu)造
}
2.iterator的使用
注意:list的迭代器和vector string不同。vector和string的迭代器都是原生指針,而list的迭代器是一個(gè)封裝起來的指針。
iterator的使用 | 接口說明 |
---|---|
begin + end | 返回第一個(gè)元素的迭代器+返回最后一個(gè)元素下一個(gè)位置的迭代器 |
rbegin + rend | 返回第一個(gè)元素的reverse_iterator(即end()位置),返回最后一個(gè)元素下一個(gè)位置的reverse_iterator(即begin()位置) |
一個(gè)正向迭代器一個(gè)反向迭代器,注意使用規(guī)則,前者++迭代器向后移動(dòng),后者++迭代器向前移動(dòng)。
test:
void test_iterator()
{int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };size_t sz = sizeof(arr) / sizeof(arr[0]);list<int> lt(arr, arr + sz);list<int>::iterator it = lt.begin();while (it != lt.end()){cout << *it << " ";++it;}cout << endl;//反向迭代器list<int>::reverse_iterator rit = lt.rbegin();while (rit != lt.rend()){cout << *rit << " ";++rit;}cout << endl;
}
3.Capacity和Element access
函數(shù)名稱 | 接口說明 |
---|---|
size | 返回list中的有效節(jié)點(diǎn)個(gè)數(shù) |
empty | 判斷是否為空 |
函數(shù)名稱 | 接口說明 |
---|---|
front | 返回list的第一個(gè)節(jié)點(diǎn)中,值的引用 |
back | 返回list的最后一個(gè)節(jié)點(diǎn)中,值的引用 |
test:
void test_capacity_elementAccsee()
{list<int> lt;lt.push_back(77);lt.push_back(22);//頭節(jié)點(diǎn)的值-尾節(jié)點(diǎn)的值lt.front() -= lt.back();cout << lt.front() << endl;cout << "size:" << lt.size() << endl;cout << "empty:" << lt.empty() << endl;
}
4.Modifiers
函數(shù)名稱 | 接口說明 |
---|---|
push_front | 頭插 |
pop_front | 頭刪 |
push_back | 尾插 |
pop_back | 尾刪 |
erase | 刪除pos位置的數(shù)據(jù) |
insert | 在pos之前插入val |
swap | 交換兩個(gè)list的元素 |
clear | 情況list的有效元素 |
test: 頭插 頭刪 尾插 尾刪
void test_Modifiers1()
{list<int> lt;//頭插lt.push_front(1);lt.push_front(2);//尾插lt.push_back(10);lt.push_back(20);//范圍forfor (auto e : lt){cout << e << " ";}cout << endl;//頭刪lt.pop_front();//尾刪lt.pop_back();for (auto e : lt){cout << e << " ";}cout << endl;
}
test: 插入 刪除 交換 清理
void test_Modifiers2()
{list<int> lt;lt.push_back(1);lt.push_back(2);lt.push_back(3);lt.push_back(4); Print(lt);//獲取鏈表第二個(gè)節(jié)點(diǎn)list<int>::iterator pos = lt.begin();cout << *(++pos) << endl;//在pos前插入值為100的元素lt.insert(pos, 100);Print(lt);//在pos前插入值5個(gè)5lt.insert(pos, 5, 5);Print(lt);//在pos前插入[v.begin(), v.end())區(qū)間的元素vector<int> v{ 6, 6, 6 ,6 };lt.insert(pos, v.begin(), v.end());Print(lt);//刪除操作//刪除pos位置上的元素 -- 特別注意一下迭代器失效問題(下個(gè)知識(shí)點(diǎn)介紹)lt.erase(pos);Print(lt);// 刪除list中[begin, end)區(qū)間中的元素,即刪除list中的所有元素lt.erase(lt.begin(), lt.end());Print(lt);list<int> lt1{ 6, 6, 6 ,6 };lt1.swap(lt);cout << "lt::empty:" << lt.empty() << endl;cout << "lt1::empty:" << lt1.empty() << endl;lt.clear();cout << "new_lt::empty:" << lt.empty() << endl;
}
5.list的迭代器失效
在list中迭代器失效即迭代器指向的節(jié)點(diǎn)是無效的,即該節(jié)點(diǎn)被刪除了。因?yàn)閘ist的底層是帶頭雙向循環(huán)列表,所以在插入元素時(shí),不會(huì)導(dǎo)致liet迭代器失效,只有刪除時(shí)指向刪除節(jié)點(diǎn)的那個(gè)迭代器失效,其他的迭代器不受影響。
錯(cuò)誤代碼:
void test_iterator_invalid()
{int arr[] = { 1,2,3,4,5,6,7,8,9,0 };size_t sz = sizeof(arr) / sizeof(arr[0]);list<int> lt(arr, arr + sz);list<int>::iterator it = lt.begin();while (it != lt.end()){//erase()執(zhí)行完之后,it所指向的節(jié)點(diǎn)已經(jīng)被刪除,因此it無效,下次使用必須重新賦值lt.erase(it);++it; //err 迭代器失效}
}
改正:
void test_iterator_invalid()
{int arr[] = { 1,2,3,4,5,6,7,8,9,0 };size_t sz = sizeof(arr) / sizeof(arr[0]);list<int> lt(arr, arr + sz);list<int>::iterator it = lt.begin();while (it != lt.end()){lt.erase(it++); //it = lt.erase(it);}
}
三、list實(shí)現(xiàn)
list類整體實(shí)現(xiàn)代碼
注意:這里就不單列出來一部分成員函數(shù)進(jìn)行介紹了,因?yàn)橹匾脑趕tring類和vector類都進(jìn)行了重點(diǎn)講解。
反向迭代器在list類實(shí)現(xiàn)中不進(jìn)行介紹,在最后單列一個(gè)知識(shí)點(diǎn)講解
#include <assert.h>namespace kpl
{// List的節(jié)點(diǎn)類template<class T>struct ListNode{ListNode<T>* _prev;ListNode<T>* _next;T _val;//初始化ListNode(const T& val = T()): _prev(nullptr), _next(nullptr), _val(val){}};//List 的迭代器:將原生態(tài)指針進(jìn)行封裝template<class T, class Ref, class Ptr>class ListIterator{typedef ListNode<T> Node;typedef ListIterator<T, Ref, Ptr> Self;public:// Ref 和 Ptr 類型重定義,在實(shí)現(xiàn)反向迭代器時(shí)便于使用。就不需要再模板傳參時(shí)傳Ref和Ptrtypedef Ref Ref;typedef Ptr Ptr;// 構(gòu)造ListIterator(Node* node = nullptr): _node(node){}// 在模板中多加一個(gè)參數(shù)Ref的原因是:區(qū)分const返回Ref operator*() { return _node->_val;}//Ptr:區(qū)分const返回Ptr operator->() { return &(operator*()); }Self& operator++(){_node = _node->_next;return *this;}Self operator++(int){Self temp(*this);_node = _node->_next;return temp;}Self& operator--(){_node = _node->_prev;return *this;}Self operator--(int){Self temp(*this);_node = _node->_prev;return temp;}// 比較bool operator!=(const Self& l)const{ return _node != l._node;}bool operator==(const Self& l)const{ return _node != l._node;}Node* _node;};//反向迭代器借用正向迭代器實(shí)現(xiàn)template<class Iterator>class ReverseListIterator{public:typedef typename Iterator::Ref Ref;typedef typename Iterator::Ptr Ptr;typedef ReverseListIterator<Iterator> Self;// 構(gòu)造ReverseListIterator(Iterator it): _it(it){}Ref operator*(){Iterator temp(_it);--temp;return *temp;}Ptr operator->(){return &(operator*());}Self& operator++(){--_it;return *this;}Self operator++(int){Self temp(*this);--_it;return temp;}Self& operator--(){++_it;return *this;}Self operator--(int){Self temp(*this);++_it;return temp;}// 比較bool operator!=(const Self& l)const{return _it != l._it;}bool operator==(const Self& l)const{return _it != l._it;}Iterator _it;};//list類模板的實(shí)現(xiàn)template<class T>class list{typedef ListNode<T> Node;public:// 正向迭代器// 這里就也可以看出傳三個(gè)模板參數(shù)的原因。不值得再去寫一個(gè)const修飾的模板,普通的迭代器和const修飾的迭代器區(qū)別就在于部分成員函數(shù)的返回值,所以多傳遞兩個(gè)參數(shù)即可typedef ListIterator<T, T&, T*> iterator;typedef ListIterator<T, const T&, const T&> const_iterator;// 反向迭代器typedef ReverseListIterator<iterator> reverse_iterator;typedef ReverseListIterator<const_iterator> const_reverse_iterator;public:// List的構(gòu)造list(){CreateHead(); //因?yàn)楹芏嗟胤蕉紩?huì)使用這部分代碼,所以進(jìn)行封裝,方便調(diào)用}list(int n, const T& value = T()){CreateHead();for (int i = 0; i < n; ++i)push_back(value);}template <class Iterator>list(Iterator first, Iterator last){CreateHead();while (first != last){push_back(*first);++first;}}//拷貝構(gòu)造list(const list<T>& l){CreateHead();// 用l中的元素構(gòu)造臨時(shí)的temp,然后與當(dāng)前對(duì)象交換。也可以一次賦值list<T> temp(l.begin(), l.end());swap(temp);}list<T>& operator=(list<T> l){swap(l);return *this;}~list(){clear();delete _head;_head = nullptr;}// List的迭代器iterator begin() { //or return _head->_next;return iterator(_head->_next); }iterator end() { //or return _head;return iterator(_head); }const_iterator begin()const { //or return _head->_next;return const_iterator(_head->_next); }const_iterator end()const{ //or return _head;return const_iterator(_head); }//反向迭代器reverse_iterator rbegin(){return reverse_iterator(end());}reverse_iterator rend(){return reverse_iterator(begin());}const_reverse_iterator rbegin()const{return const_reverse_iterator(end());}const_reverse_iterator rend()const{return const_reverse_iterator(begin());}// capacity相關(guān)size_t size()const{//在實(shí)現(xiàn)size時(shí),也可以通過給list類增減一個(gè)size_t類型的成員變量,然后返回Node* cur = _head->_next;size_t count = 0;while (cur != _head){count++;cur = cur->_next;}return count;}bool empty()const{return _head->_next == _head;}void resize(size_t newsize, const T& data = T()){size_t oldsize = size();if (newsize <= oldsize){// 有效元素個(gè)數(shù)減少到newsizewhile (newsize < oldsize){pop_back();oldsize--;}}else{while (oldsize < newsize){push_back(data);oldsize++;}}}// List的元素訪問操作// 注意:List不支持operator[]T& front(){return _head->_next->_val;}const T& front()const{return _head->_next->_val;}T& back(){return _head->_prev->_val;}const T& back()const{return _head->_prev->_val;}// List的插入和刪除void push_back(const T& val) { insert(end(), val); }void pop_back() { erase(--end()); }void push_front(const T& val) { insert(begin(), val); }void pop_front() { erase(begin()); }// 在pos位置前插入值為val的節(jié)點(diǎn)iterator insert(iterator pos, const T& val){Node* pNewNode = new Node(val);Node* cur = pos._node;// 先將新節(jié)點(diǎn)插入pNewNode->_prev = cur->_prev;pNewNode->_next = cur;pNewNode->_prev->_next = pNewNode;cur->_prev = pNewNode;return iterator(pNewNode);}// 刪除pos位置的節(jié)點(diǎn),返回該節(jié)點(diǎn)的下一個(gè)位置iterator erase(iterator pos){assert(pos != end());Node* cur = pos._node;Node* prev = cur->_prev;Node* next = cur->_next;prev->_next = next;next->_prev = prev;delete cur;return next;}void clear(){iterator it = begin();while (it != end()){it = erase(it);}_head->_next = _head->_prev = _head;}void swap(list<T>& l){std::swap(_head, l._head);}private:void CreateHead(){_head = new Node;_head->_prev = _head;_head->_next = _head;}private:Node* _head;};
}
四、vector 和 list 對(duì)比
vector | list | |
---|---|---|
底 層 結(jié) 構(gòu) | 動(dòng)態(tài)順序表,一段連續(xù)空間 | 帶頭結(jié)點(diǎn)的雙向循環(huán)鏈表 |
訪 問 | 支持隨機(jī)訪問,訪問某個(gè)元素效率O(1) | 不支持隨機(jī)訪問,訪問某個(gè)元素效率O(N) |
插 入 和 刪 除 | 任意位置插入和刪除效率低,需要搬移元素,時(shí)間復(fù)雜度為O(N),插入時(shí)有可能需要增容,增容:開辟新空間,拷貝元素,釋放舊空間,導(dǎo)致效率更低 | 任意位置插入和刪除效率高,不需要搬移元素,時(shí)間復(fù)雜度為O(1) |
空 間 利 用 率 | 底層為連續(xù)空間,不容易造成內(nèi)存碎片,空間利用率高,緩存利用率高 | 底層節(jié)點(diǎn)動(dòng)態(tài)開辟,小節(jié)點(diǎn)容易造成內(nèi)存碎片,空間利用率低,緩存利用率低 |
迭 代 器 | 原生態(tài)指針 | 對(duì)原生態(tài)指針(節(jié)點(diǎn)指針)進(jìn)行封裝 |
代 器 失 效 | 在插入元素時(shí),要給所有的迭代器重新賦值,因?yàn)椴迦朐赜锌赡軙?huì)導(dǎo)致重新擴(kuò)容,致使原來迭代器失效,刪除時(shí),當(dāng)前迭代器需要重新賦值否則會(huì)失效 | 插入元素不會(huì)導(dǎo)致迭代器失效,刪除元素時(shí),只會(huì)導(dǎo)致當(dāng)前迭代器失效,其他迭代器不受影響 |
使 用 場(chǎng) 景 | 需要高效存儲(chǔ),支持隨機(jī)訪問,不關(guān)心插入刪除效率 | 大量插入和刪除操作,不關(guān)心隨機(jī)訪問 |
五、迭代器
1.迭代器的實(shí)現(xiàn)
迭代器有兩種實(shí)現(xiàn)方式,具體應(yīng)根據(jù)容器底層數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn):
- 原生態(tài)指針,比如:vector
- 將原生態(tài)指針進(jìn)行封裝,因迭代器使用形式與指針完全相同,因此在自定義的類中必須實(shí)現(xiàn)以下方法:
- 指針可以解引用,迭代器的類中必須重載operator*()
- 指針可以通過->訪問其所指空間成員,迭代器類中必須重載oprator->()
- 指針可以++向后移動(dòng),迭代器類中必須重載operator++()與operator++(int)
- 指針可以通過->訪問其所指空間成員,迭代器類中必須重載oprator->()。至于operator–()/operator–(int)釋放需要重載,根據(jù)具體的結(jié)構(gòu)來抉擇,雙向鏈表可以向前移動(dòng),所以需要重載,如果是forward_list(單鏈表)就不需要重載–。
- 迭代器需要進(jìn)行是否相等的比較,因此還需要重載operator==()與operator!=()
2.迭代器的分類(按照功能分類)
- 單向迭代器的功能相對(duì)較少,只能進(jìn)行逐個(gè)元素的遍歷和訪問操作。它只支持t運(yùn)算符來移動(dòng)到下一個(gè)元素,不支持–運(yùn)算符來回退到前一個(gè)元素。因此,單向迭代器無法進(jìn)行逆向遍歷和隨機(jī)訪問元素的操作。
- 雙向迭代器相比于單向迭代器功能更加強(qiáng)大,它支持雙向即可以使用++運(yùn)算符向前移動(dòng)到下一個(gè)元素,也可以使用–運(yùn)算符向后移動(dòng)到前一個(gè)元素。因此,雙向迭代器可以進(jìn)行逆向遍歷和前向遍歷操作。
- 隨機(jī)迭代器是迭代器的最高級(jí)別,功能最豐富。它除了支持雙向迭代器的所有操作外,還可以進(jìn)行隨機(jī)訪問,即可以使用]運(yùn)算符來訪問任意位置的元素。此外,隨機(jī)迭代器還可以進(jìn)行迭代器之間的算術(shù)運(yùn)算,比如可以使用+、-運(yùn)算符來計(jì)算迭代器之間的距離。
所以,單向迭代器功能最少,只能逐個(gè)訪問元素;雙向迭代器比單向迭代器功能更強(qiáng)大,可以雙向移動(dòng);隨機(jī)迭代器是最高級(jí)別的迭代器,功能最豐富,除了雙向移動(dòng)外還能進(jìn)行隨機(jī)訪問和算術(shù)運(yùn)算操作。
3.反向迭代器
(1)、包裝邏輯
(2)、代碼
template<class Iterator>class ReverseListIterator{// 注意:此處typename的作用是明確告訴編譯器,Ref是Iterator類中的一個(gè)類型,而不是靜態(tài)成員變量// 否則編譯器編譯時(shí)就不知道Ref是Iterator中的類型還是靜態(tài)成員變量// 因?yàn)殪o態(tài)成員變量也是按照 類名::靜態(tài)成員變量名 的方式訪問的//typename和class的區(qū)別會(huì)在模板的博客中進(jìn)行介紹public:typedef typename Iterator::Ref Ref;typedef typename Iterator::Ptr Ptr;typedef ReverseListIterator<Iterator> Self;public:// 構(gòu)造ReverseListIterator(Iterator it): _it(it){}Ref operator*(){Iterator temp(_it);--temp;return *temp;}Ptr operator->(){return &(operator*());}Self& operator++(){--_it;return *this;}Self operator++(int){Self temp(*this);--_it;return temp;}Self& operator--(){++_it;return *this;}Self operator--(int){Self temp(*this);++_it;return temp;}bool operator!=(const Self& l)const{return _it != l._it;}bool operator==(const Self& l)const{return _it != l._it;}Iterator _it;};
注意
//迭代器對(duì)箭頭進(jìn)行了重載,返回的是一個(gè)指針Ptr operator->(){return &(operator*());}
雖然重載了->但是在使用的時(shí)候,會(huì)發(fā)現(xiàn)一個(gè)問題。
eg:
struct A
{A(int a1 = 0, int a2 = 0):_a1(a1), _a2(a2){}int _a1;int _a2;
};void test_iterator()
{list<A> lt;lt.push_back(A(1, 1));lt.push_back(A(2, 2));lt.push_back(A(3, 3));list<A>::iterator it = lt.begin();while (it != lt.end()){cout << (*it)._a1 << " " << (*it)._a2 << endl;cout << it->_a1 << " " << it->_a2 << endl;++it;}cout << endl;
}