本文主要介紹c++:stl中l(wèi)ist常用接口的功能及使用方法,比較list與vector的區(qū)別,并對(duì)list的常用接口進(jìn)行模擬實(shí)現(xiàn)。
目錄
一、list的介紹和使用
1.list介紹
2.list使用
1.list的構(gòu)造
2.list iterator的使用
3.list 容量相關(guān)
4.list元素訪問
5.list修改
6.list的迭代器失效
二、list的模擬實(shí)現(xiàn)
1.list的節(jié)點(diǎn)類
2.list的迭代器類
1.正向迭代器
2.反向迭代器
3.list類
三、list和vector的對(duì)比
一、list的介紹和使用
1.list介紹
list文檔介紹
1. list是可以在常數(shù)范圍內(nèi)在任意位置進(jìn)行插入和刪除的序列式容器,并且該容器可以前后雙向迭代。
2. list的底層是雙向鏈表結(jié)構(gòu),雙向鏈表中每個(gè)元素存儲(chǔ)在互不相關(guān)的獨(dú)立節(jié)點(diǎn)中,在節(jié)點(diǎn)中通過指針指向其前一個(gè)元素和后一個(gè)元素。
3. list與forward_list非常相似:最主要的不同在于forward_list是單鏈表,只能朝前迭代,已讓其更簡(jiǎn)單高效。
4. 與其他的序列式容器相比(array,vector,deque),list通常在任意位置進(jìn)行插入、移除元素的執(zhí)行效率更好。
5. 與其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的隨機(jī)訪問,比如:要訪問list 的第6個(gè)元素,必須從已知的位置(比如頭部或者尾部)迭代到該位置,在這段位置上迭代需要線性的時(shí)間開銷;list還需要一些額外的空間,以保存每個(gè)節(jié)點(diǎn)的相關(guān)聯(lián)信息(對(duì)于存儲(chǔ)類型較小元素的大list來(lái)說(shuō)這可能是一個(gè)重要的因素)
2.list使用
list中的接口比較多,此處類似,只需要掌握如何正確的使用,然后再去深入研究背后的原理,已達(dá)到可擴(kuò)展的能力。以下為list中一些常見的重要接口。
1.list的構(gòu)造
構(gòu)造函數(shù) | 接口說(shuō)明 |
---|---|
list (size_type n, const value_type& val = value_type()) | 構(gòu)造的list中包含n個(gè)值為val的元素 |
list() | 構(gòu)造空的list |
list (const list& x) | 拷貝構(gòu)造函數(shù) |
list (InputIterator first, InputIterator last) | 用[first, last)區(qū)間中的元素構(gòu)造list |
void test1()
{
list<int> lt1; // 構(gòu)造空的lt1
list<int> lt2(4, 100); // lt2中放4個(gè)值為100的元素
list<int> lt3(lt2.begin(), lt2.end()); //用lt2的[begin(), end())左閉右開的區(qū)間構(gòu)造lt3
list<int> lt4(lt3); // 用lt3拷貝構(gòu)造lt4
// 以數(shù)組為迭代器區(qū)間構(gòu)造l5
int array[] = { 10,20,30,40 };
list<int> lt5(array, array + sizeof(array) / sizeof(int));
// 列表格式初始化C++11
list<int> lt6{ 1,2,3,4,5 };
// 用迭代器方式打印l5中的元素
list<int>::iterator it = lt5.begin();
while (it != lt5.end())
{
cout << *it << " ";
++it;
}
cout << endl;
//10 20 30 40
// C++11范圍for的方式遍歷
for (auto& e : lt5)
cout << e << " ";
cout << endl;
//10 20 30 40
}
2.list iterator的使用
此處可以將迭代器理解成一個(gè)指針,該指針指向list中的某個(gè)節(jié)點(diǎn)。
函數(shù)聲明 | 接口說(shuō)明 |
---|---|
begin + end | 返回第一個(gè)元素的迭代器+返回最后一個(gè)元素下一個(gè)位置的迭代器 |
rbegin + rend | 返回第一個(gè)元素的reverse_iterator,即end位置,返回最后一個(gè)元素下一個(gè)位置的 reverse_iterator,即begin位置 |
void test2()
{
int array[] = { 1, 2, 3, 4, 5};
list<int> lt(array, array + sizeof(array) / sizeof(array[0]));
// 使用正向迭代器正向list中的元素
// list<int>::iterator it = l.begin(); // C++98中語(yǔ)法
auto it = lt.begin(); // C++11之后推薦寫法
while (it != lt.end())
{
cout << *it << " ";
++it;
}
cout << endl;//1 2 3 4 5
// 使用反向迭代器逆向打印list中的元素
// list<int>::reverse_iterator rit = l.rbegin();
auto rit = lt.rbegin();
while (rit != lt.rend())
{
cout << *rit << " ";
++rit;
}
cout << endl;//1 2 3 4 5
}
注意:
1. begin與end為正向迭代器,對(duì)迭代器執(zhí)行++操作,迭代器向后移動(dòng)
2. rbegin(end)與rend(begin)為反向迭代器,對(duì)迭代器執(zhí)行++操作,迭代器向前移動(dòng)
3.list 容量相關(guān)
函數(shù)聲明 | 接口說(shuō)明 |
---|---|
empty | 檢測(cè)list是否為空,是返回true,否則返回false |
size | 返回list中有效節(jié)點(diǎn)的個(gè)數(shù) |
void test3()
{
int array[] = { 1, 2, 3, 4, 5 };
list<int> lt(array, array + sizeof(array) / sizeof(array[0]));
if (!lt.empty())
cout << "false" << endl;//false
cout<<lt.size() << endl;//5
}
4.list元素訪問
函數(shù)聲明 | 接口說(shuō)明 |
---|---|
front | 返回list的第一個(gè)節(jié)點(diǎn)中值的引用 |
back | 返回list的最后一個(gè)節(jié)點(diǎn)中值的引用 |
void test4()
{
int array[] = { 1, 2, 3, 4, 5 };
list<int> lt(array, array + sizeof(array) / sizeof(array[0]));
cout << lt.front() << endl;//1
cout << lt.back() << endl;//5
}
5.list修改
函數(shù)聲明 | 接口說(shuō)明 |
---|---|
push_front | 在list首元素前插入值為val的元素 |
pop_front | 刪除list中第一個(gè)元素 |
push_back | 在list尾部插入值為val的元素 |
pop_back | 刪除list中最后一個(gè)元素 |
insert | 在list position 位置中插入值為val的元素 |
erase | 刪除list position位置的元素 |
swap | 交換兩個(gè)list中的元素 |
clear | 清空l(shuí)ist中的有效元素 |
void PrintList(const list<int>& lt)
{
// 注意這里調(diào)用的是list的 begin() const,返回list的const_iterator對(duì)象
for (list<int>::const_iterator it = lt.begin(); it != lt.end(); ++it)
{
cout << *it << " ";
// *it = 10; 編譯不通過
}
cout << endl;
}
// push_back/pop_back/push_front/pop_front
void test5()
{
int array[] = { 1, 2, 3 };
list<int> lt(array, array + sizeof(array) / sizeof(array[0]));
// 在list的尾部插入4,頭部插入0
lt.push_back(4);
lt.push_front(0);
PrintList(lt);//0 1 2 3 4
// 刪除list尾部節(jié)點(diǎn)和頭部節(jié)點(diǎn)
lt.pop_back();
lt.pop_front();
PrintList(lt);//1 2 3
}
// insert /erase
void test6()
{
int array1[] = { 1, 2, 3 };
list<int> lt(array1, array1 + sizeof(array1) / sizeof(array1[0]));
// 獲取鏈表中第二個(gè)節(jié)點(diǎn)
auto pos = ++lt.begin();
cout << *pos << endl;//2
// 在pos前插入值為4的元素
lt.insert(pos, 4);
PrintList(lt);//1 4 2 3
// 在pos前插入5個(gè)值為5的元素
lt.insert(pos, 5, 5);
PrintList(lt);//1 4 5 5 5 5 5 2 3
// 在pos前插入[v.begin(), v.end)區(qū)間中的元素
vector<int> v{ 7, 8, 9 };
lt.insert(pos, v.begin(), v.end());
PrintList(lt);//1 4 5 5 5 5 5 7 8 9 2 3
// 刪除pos位置上的元素
lt.erase(pos);
PrintList(lt);//1 4 5 5 5 5 5 7 8 9 3
// 刪除list中[begin, end)區(qū)間中的元素,即刪除list中的所有元素
lt.erase(lt.begin(), lt.end());
PrintList(lt);//
}
// resize/swap/clear
void test7()
{
// 用數(shù)組來(lái)構(gòu)造list
int array1[] = { 1, 2, 3 };
list<int> lt1(array1, array1 + sizeof(array1) / sizeof(array1[0]));
PrintList(lt1);//1 2 3
// 交換l1和l2中的元素
list<int> lt2;
lt1.swap(lt2);
PrintList(lt1);//
PrintList(lt2);//1 2 3
// 將l2中的元素清空
lt2.clear();
cout << lt2.size() << endl;//0
}
list中還有一些操作,需要用到時(shí)可參閱list的文檔說(shuō)明。
6.list的迭代器失效
前面說(shuō)過,此處可將迭代器暫時(shí)理解成類似于指針,迭代器失效即迭代器所指向的節(jié)點(diǎn)的無(wú)效,即該節(jié)點(diǎn)被刪除了。因?yàn)?strong>list的底層結(jié)構(gòu)為帶頭結(jié)點(diǎn)的雙向循環(huán)鏈表,因此在list中進(jìn)行插入時(shí)是不會(huì)導(dǎo)致list的迭代器失效的,只有在刪除時(shí)才會(huì)失效,并且失效的只是指向被刪除節(jié)點(diǎn)的迭代器,其他迭代器不會(huì)受到影響。
void TestListIterator1()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> lt(array, array + sizeof(array) / sizeof(array[0]));
auto it = lt.begin();
while (it != lt.end())
{
// erase()函數(shù)執(zhí)行后,it所指向的節(jié)點(diǎn)已被刪除,
// 因此it無(wú)效,在下一次使用it時(shí),必須先給其賦值
lt.erase(it);
++it;
}
}
// 改正
void TestListIterator2()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> lt(array, array + sizeof(array) / sizeof(array[0]));
auto it = lt.begin();
while (it != lt.end())
{
lt.erase(it++); // it = l.erase(it);
}
}
二、list的模擬實(shí)現(xiàn)
1.list的節(jié)點(diǎn)類
template<class T>
struct ListNode
{
ListNode(const T& val = T())
:_prev(nullptr)
, _next(nullptr)
, _val(val)
{}
ListNode<T>* _prev;
ListNode<T>* _next;
T _val;
};
2.list的迭代器類
1.正向迭代器
迭代器有兩種實(shí)現(xiàn)方式,具體應(yīng)根據(jù)容器底層數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn):
1. 原生態(tài)指針,比如:vector
2. 將原生態(tài)指針進(jìn)行封裝,因迭代器使用形式與指針完全相同,因此在自定義的類中必須實(shí)現(xiàn)以下方法:
????????1. 指針可以解引用,迭代器的類中必須重載operator*()
????????2. 指針可以通過->訪問其所指空間成員,迭代器類中必須重載oprator->()
????????3. 指針可以++向后移動(dòng),迭代器類中必須重載operator++()與operator++(int)
????????至于operator--()/operator--(int)釋放需要重載,根據(jù)具體的結(jié)構(gòu)來(lái)抉擇,雙向鏈表可以向前移動(dòng),所以需要重載,如果是forward_list就不需要重載--
????????4. 迭代器需要進(jìn)行是否相等的比較,因此還需要重載operator==()與operator!=()
template<class T, class Ref, class Ptr>
//Ref和Ptr分布表示 T& 和 T* 或者const T& 和const T*
class ListIterator
{
typedef ListNode<T> Node;
typedef ListIterator<T, Ref, Ptr> Self;
// Ref 和 Ptr 類型需要重定義下,實(shí)現(xiàn)反向迭代器時(shí)需要用到
public:
typedef Ref Ref;
typedef Ptr Ptr;
public:
Node* _node;
// 構(gòu)造
ListIterator(Node* node = nullptr)
: _node(node)
{}
// 具有指針類似行為
Ref operator*()
{
return _node->_val;
}
Ptr operator->()
{
return &(operator*());
}
// 迭代器移動(dòng)
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;
}
};
2.反向迭代器
通過前面例子知道,反向迭代器的++就是正向迭代器的--,反向迭代器的--就是正向迭代器的++,因此反向迭代器的實(shí)現(xiàn)可以借助正向迭代器,即:反向迭代器內(nèi)部可以包含一個(gè)正向迭代器,對(duì)正向迭代器的接口進(jìn)行包裝即可。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-730006.html
template<class Iterator>
class ReverseListIterator
{
// 注意:此處typename的作用是明確告訴編譯器,Ref是Iterator類中的一個(gè)類型,而不是靜態(tài)成員變量
// 否則編譯器編譯時(shí)就不知道Ref是Iterator中的類型還是靜態(tài)成員變量
// 因?yàn)殪o態(tài)成員變量也是按照類名::靜態(tài)成員變量名的方式訪問的
public:
typedef typename Iterator::Ref Ref;
typedef typename Iterator::Ptr Ptr;
typedef ReverseListIterator<Iterator> Self;
public:
Iterator _it;
// 構(gòu)造
ReverseListIterator(Iterator it)
: _it(it)
{}
// 具有指針類似行為
Ref operator*()
{
Iterator temp(_it);
--temp;
return *temp;
}
Ptr operator->()
{
return &(operator*());
}
// 迭代器移動(dòng)
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;
}
};
3.list類
template<class T>
class list
{
typedef ListNode<T> Node;
public:
// 正向迭代器
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();
}
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;
}
}
list(const list<T>& l)
{
CreateHead();
// 用l中的元素構(gòu)造臨時(shí)的temp,然后與當(dāng)前對(duì)象交換
list<T> temp(l.begin(), l.end());
this->swap(temp);
}
list<T>& operator=(list<T> l)
{
this->swap(l);
return *this;
}
~list()
{
clear();
delete _head;
_head = nullptr;
}
// List的迭代器
iterator begin()
{
return iterator(_head->_next);
}
iterator end()
{
return iterator(_head);
}
const_iterator begin()const
{
return const_iterator(_head->_next);
}
const_iterator end()const
{
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());
}
// List的容量相關(guān)
size_t size()const
{
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ù)減少到newsize
while (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* pCur = pos._node;
// 先將新節(jié)點(diǎn)插入
pNewNode->_prev = pCur->_prev;
pNewNode->_next = pCur;
pNewNode->_prev->_next = pNewNode;
pCur->_prev = pNewNode;
return iterator(pNewNode);
}
// 刪除pos位置的節(jié)點(diǎn),返回該節(jié)點(diǎn)的下一個(gè)位置
iterator erase(iterator pos)
{
// 找到待刪除的節(jié)點(diǎn)
Node* pDel = pos._node;
Node* pRet = pDel->_next;
// 將該節(jié)點(diǎn)從鏈表中拆下來(lái)并刪除
pDel->_prev->_next = pDel->_next;
pDel->_next->_prev = pDel->_prev;
delete pDel;
return iterator(pRet);
}
void clear()
{
Node* cur = _head->_next;
// 采用頭刪除刪除
while (cur != _head)
{
_head->_next = cur->_next;
delete cur;
cur = _head->_next;
}
_head->_next = _head->_prev = _head;
}
void swap(bite::list<T>& l)
{
std::swap(_head, l._head);
}
private:
void CreateHead()
{
_head = new Node;
_head->_prev = _head;
_head->_next = _head;
}
private:
Node* _head;
};
三、list和vector的對(duì)比
vector與list都是STL中非常重要的序列式容器,由于兩個(gè)容器的底層結(jié)構(gòu)不同,導(dǎo)致其特性以及應(yīng)用場(chǎng)景不同,其主要不同如下:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-730006.html
vector | list | |
---|---|---|
底 層 結(jié) 構(gòu) | 動(dòng)態(tài)順序表,一段連續(xù)空間 | 帶頭結(jié)點(diǎn)的雙向循環(huán)鏈表 |
隨 機(jī) 訪 問 | 支持隨機(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ò)容,致使原來(lái)迭代器失效,刪 除時(shí),當(dāng)前迭代器需要重新賦值否則會(huì)失效 | 插入元素不會(huì)導(dǎo)致迭代器失效, 刪除元素時(shí),只會(huì)導(dǎo)致當(dāng)前迭代 器失效,其他迭代器不受影響 |
使 用 場(chǎng) 景 | 需要高效存儲(chǔ),支持隨機(jī)訪問,不關(guān)心插入刪除效率 | 大量插入和刪除操作,不關(guān)心隨機(jī)訪問 |
到了這里,關(guān)于C++:stl:list的常用接口及其模擬實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!