自学内容网 自学内容网

STL篇三:list

前言

  前面学习的string与vector都是线性结构,本节介绍的list是我们遇到的第一个链式结构,此部分的迭代器封装比较难以理解,希望大家都能学有所成,学有所获。

1.list的介绍和使用

1.1 list的介绍

list的介绍文档

  1. list是可以在常数范围内在任意位置进行插入和删除的序列式容器,并且该容器可以前后双向迭代。
  2. list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素。
  3. list与forward_list非常相似:最主要的不同在于forward_list是单链表,只能朝前迭代,已让其更简单高
    效。
  4. 与其他的序列式容器相比(array,vector,deque),list通常在任意位置进行插入、移除元素的执行效率
    更好。
  5. 与其他序列式容器相比,list和forward_list最大的缺陷是不支持任意位置的随机访问,比如:要访问list
    的第6个元素,必须从已知的位置(比如头部或者尾部)迭代到该位置,在这段位置上迭代需要线性的时间开销;list还需要一些额外的空间,以保存每个节点的相关联信息(对于存储类型较小元素的大list来说这可能是一个重要的因素)

1.2 list的使用

#include <iostream>
using namespace std;
#include <list>
#include <vector>
// list的构造
void TestList1()
{
    list<int> l1;                         // 构造空的l1
    list<int> l2(4, 100);                 // l2中放4个值为100的元素
    list<int> l3(l2.begin(), l2.end());  // 用l2的[begin(), end())左闭右开的区间构造l3
    list<int> l4(l3);                    // 用l3拷贝构造l4

    // 以数组为迭代器区间构造l5
    int array[] = { 16,2,77,29 };
    list<int> l5(array, array + sizeof(array) / sizeof(int));

    // 列表格式初始化C++11
    list<int> l6{ 1,2,3,4,5 };

    // 用迭代器方式打印l5中的元素
    list<int>::iterator it = l5.begin();
    while (it != l5.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    // C++11范围for的方式遍历
    for (auto& e : l5)
        cout << e << " ";

    cout << endl;
}


// list迭代器的使用
// 注意:遍历链表只能用迭代器和范围for
void PrintList(const list<int>& l)
{
    // 注意这里调用的是list的 begin() const,返回list的const_iterator对象
    for (list<int>::const_iterator it = l.begin(); it != l.end(); ++it)
    {
        cout << *it << " ";
        // *it = 10; 编译不通过
    }

    cout << endl;
}

void TestList2()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    list<int> l(array, array + sizeof(array) / sizeof(array[0]));
    // 使用正向迭代器正向list中的元素
    // list<int>::iterator it = l.begin();   // C++98中语法
    auto it = l.begin();                     // C++11之后推荐写法
    while (it != l.end())
    {
        cout << *it << " ";
        ++it;
    }
    cout << endl;

    // 使用反向迭代器逆向打印list中的元素
    // list<int>::reverse_iterator rit = l.rbegin();
    auto rit = l.rbegin();
    while (rit != l.rend())
    {
        cout << *rit << " ";
        ++rit;
    }
    cout << endl;
}


// list插入和删除
// push_back/pop_back/push_front/pop_front
void TestList3()
{
    int array[] = { 1, 2, 3 };
    list<int> L(array, array + sizeof(array) / sizeof(array[0]));

    // 在list的尾部插入4,头部插入0
    L.push_back(4);
    L.push_front(0);
    PrintList(L);

    // 删除list尾部节点和头部节点
    L.pop_back();
    L.pop_front();
    PrintList(L);
}

// insert /erase 
void TestList4()
{
    int array1[] = { 1, 2, 3 };
    list<int> L(array1, array1 + sizeof(array1) / sizeof(array1[0]));

    // 获取链表中第二个节点
    auto pos = ++L.begin();
    cout << *pos << endl;

    // 在pos前插入值为4的元素
    L.insert(pos, 4);
    PrintList(L);

    // 在pos前插入5个值为5的元素
    L.insert(pos, 5, 5);
    PrintList(L);

    // 在pos前插入[v.begin(), v.end)区间中的元素
    vector<int> v{ 7, 8, 9 };
    L.insert(pos, v.begin(), v.end());
    PrintList(L);

    // 删除pos位置上的元素
    L.erase(pos);
    PrintList(L);

    // 删除list中[begin, end)区间中的元素,即删除list中的所有元素
    L.erase(L.begin(), L.end());
    PrintList(L);
}

// resize/swap/clear
void TestList5()
{
    // 用数组来构造list
    int array1[] = { 1, 2, 3 };
    list<int> l1(array1, array1 + sizeof(array1) / sizeof(array1[0]));
    PrintList(l1);

    // 交换l1和l2中的元素
    list<int> l2;
    l1.swap(l2);
    PrintList(l1);
    PrintList(l2);

    // 将l2中的元素清空
    l2.clear();
    cout << l2.size() << endl;
}

1.3 list的迭代器的失效

  前面说过,此处大家可将迭代器暂时理解成类似于指针,迭代器失效即迭代器所指向的节点的无效,即该节点被删除了。因为list的底层结构为带头结点的双向循环链表,因此在list中进行插入时是不会导致list的迭代器失效的,只有在删除时才会失效,并且失效的只是指向被删除节点的迭代器,其他迭代器不会受到影响。

void TestListIterator1()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
// erase()函数执行后,it所指向的节点已被删除,因此it无效,在下一次使用it时,必须先给其赋值
l.erase(it);
++it;
}
}
// 改正
void TestListIterator()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
list<int> l(array, array + sizeof(array) / sizeof(array[0]));
auto it = l.begin();
while (it != l.end())
{
l.erase(it++); // it = l.erase(it);
}
}

2.list的模拟实现

2.1 结点的封装

  在 list 中存放的都是一个一个的节点,而一个节点又包含数据域以及指针域,因此需要对节点进行封装,便于存储到 list 中。

template <class T>
struct list_node
{
T _data;
struct list_node<T>* _next;
struct list_node<T>* _prev;

list_node(const T& x = T())
:_data(x)
,_next(nullptr)
,_prev(nullptr)
{}
};

2.2 迭代器的封装

2.2.1 正向迭代器

  因为 list 中迭代器的解引用以及 ++ 都无法像 vector 和 string 中那样使用,因此需要对迭代器进行封装实现这些功能。迭代器本质上也是在对节点进行运算,因此它的成员也是 Node*,参考 list::iterator it = lt.begin(),lt.begin()返回的就是一个节点的地址。

template <class T, class Ref, class Ptr>
struct __list_iterator
{
typedef list_node<T> Node;
typedef __list_iterator<T, Ref, Ptr> self;

Node* _node;

__list_iterator(Node* node)
:_node(node)
{}

Ref operator*()
{
return _node->_data;
}

Ptr operator->()
{
return &_node->_data;
}

self& operator++()
{
_node = _node->_next;
return *this; 
}

self& operator--()
{
_node = _node->_prev;
return *this;
}

self operator++(int)
{
self tmp(*this);
_node = _node->_next;
return tmp;
}

self operator--(int)
{
self tmp(*this);
_node = _node->_prev;
return tmp;
}

bool operator!=(const self& s)
{
return _node != s._node;
}

bool operator==(const self& s)
{
return _node == s._node; 
}
};

  有一个点需要讲解一下的是 -> 的重载,它返回的是结点数据的指针,可能会有点看不懂,我们来看一个例子:

class AA
{
public:
AA(int a1 = 0, int a2 = 0)
: _a1(a1)
, _a2(a2)
{}

int _a1;
int _a2;
};

void test_list5()
{
list<AA> lt;
lt.push_back(AA(1, 1));
lt.push_back(AA(2, 2));
lt.push_back(AA(3, 3));

list<AA>::iterator it = lt.begin();
while (it != lt.end())
{
cout << (*it)._a1 <<" " <<  (*it)._a2 <<endl;
cout << it->_a1 << " " << it->_a2 << endl;
//实际上应该是:it->->_a1    it->->_a2
++it;
}
}

  ->重载返回的是一个指针,所以实际上应该是需要两个箭头,第一个箭头是重载的箭头,第二个用来对返回的地址进行解引用的,但是由于两个箭头观赏性不好,就规定写的时候只写一个箭头。
  首先要说明的是模板参数,template <class T, class Ref, class Ptr>大家可以对这个会有所困惑,对于一个迭代器,有非const迭代器,那么肯定也就有const迭代器,如果像之前那么写自然是可以的,但是我们如果实现了一个非const迭代器后,如果还需要使用到const迭代器,那么我们就需要重新将所有功能再实现一遍。

template <class t>
struct __list_const_iterator
{
typedef struct list_node<t> node;
typedef __list_const_iterator<t> self;

Node* _node;

__list_const_iterator(node* node)
:_node(node)
{}

const t& operator*()
{
return _node->_data;
}

const t* operator->()
{
return &_node->_data;
}

self& operator++()
{
_node = _node->_next;
return *this;
}

self& operator--()
{
_node = _node->_prev;
return *this;
}

self operator++(int)
{
self tmp(*this);
_node = _node->_next;
return tmp;
}

self operator--(int)
{
self tmp(*this);
_node = _node->_prev;
return tmp;
}

bool operator!=(const self& s)
{
return _node != s._node;
}

bool operator==(const self& s)
{
return _node == s._node;
}
};

  就像这样,我们需要将所有已经实现过的功能再实现一遍,仅仅只是添加了一些const,那么有没有什么方法可以解决这种问题呢?那就是我 上面所写的template <class T, class Ref, class Ptr>这种方式,它增加了两个模板参数,一个是指T类型的引用,一个是指T类型的指针。我们在使用时只需要进行实例化,就可以完美的避免上面这种繁琐的情况。

typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;

  至于为什么需要三个模板参数,是分别对应其本身的值 、其引用和其地址三种情况的。还需要注意一下的是区分前置++和后置++,在对其前置++进行重载时()里是空的,后置++的()里是写了int,也就是函数重载,通过对函数参数的不同来区分前置++和后置++。

2.2.2 反向迭代器

  反向迭代器可以用正向迭代器来封装,

template<class iterator,class Ref,class Ptr>
class Reverse_Iterator
{
public:
typedef Reverse_Iterator Self;
Reverse_Iterator(iterator it)
:_it(it)
{}

Self& operator++()
{
--_it;
return *this;
}

bool operator!=(const Self& it)
{
return _it != it._it;
}

Ref operator*()
{
return *_it;
}

Ref operator->()
{
return _it.operator();
}

private:
iterator _it;
};

2.3 list功能的实现

2.3.1 迭代器的实例化及begin()、end()

  由于迭代器在类的外面也需要进行使用,因此在实例化时需要放到public中,而上面封装的迭代器可以理解为它只是个模板,在这实例化后才会有相应的迭代器。

template<class T>
class list
{
// 只在类域里面使用,所以设置为私有,在 class 默认为私有,在 struct 中默认为公有
typedef struct list_node<T> Node;

public:

// 在类域外面也需要使用,因此要放到 public 里面
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
//typedef __list_const_iterator<T> const_iterator;

typedef Reverse_Iterator<iterator, T&, T*> reverse_iterator;
typedef Reverse_Iterator<const_iterator, const T&, const T*> const_reverse_iterator;
reverse_iterator rbegin()
{
return --end();
}

reverse_iterator rend()
{
return end();
}

const_iterator begin()const
{
return _head->_next;
}

const_iterator end()const
{
return _head;
}

iterator begin()
{
return _head->_next;
}

iterator end()
{
return _head;
}

2.3.2 构造函数

  list的底层是双向循环链表,包含一个数据域和两个指针域。

void empty_init()
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
}

list()
{
empty_init();
}

list(const list<T>& lt)
{
empty_init();

for (auto e : lt)
{
push_back(e);
}
}

2.3.3 赋值运算符重载

  这样实现的原理与vector中的赋值运算符重载一模一样,不懂的小伙伴可以去上一篇文章中进行详细阅读。

void swap(const list<T>& lt)
{
std::swap(_head, lt._head);
std::swap(_size, lt._size);
}

list<T>& operator=(list<T> lt)
{
swap(lt);
return *this;
}

2.3.4 清除

  从头到尾一个一个进行删除就可以了。

void clear()
{
iterator it = begin();
while (it != end())
{
it = erase(it);
}
}

2.3.5 尾插

  后续部分的内容与前面的双向循环链表中的一样,如果不明白具体过程的小伙伴可以进行跳转链接观看,在双向循环链表中有详细图解。

void push_back(const T& x)
{
//Node* newnode = new Node(x);
//Node* tail = _head->_prev;

//_head->_prev = newnode;
//newnode->_next = _head;

//tail->_next = newnode;
//newnode->_prev = tail;

insert(end(), x);
}

2.3.6 任意位置插入

iterator insert(iterator pos, const T& val)
{
Node* newnode = new Node(val);

Node* prev = pos._node->_prev;

// prev  newnode  pos._node <------ 三个结点的位置关系
newnode->_next = pos._node;
pos._node->_prev = newnode;

newnode->_prev = prev;
prev->_next = newnode;
_size++;

return iterator(newnode);
}

2.3.7 删除任意位置元素

iterator erase(iterator pos)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* next = cur->_next;

prev->_next = next;
next ->_prev = prev;
_size--;

return iterator(next);
}

2.3.8 头插

  直接复用插入即可。

void push_front(const T& x)
{
insert(begin(), x);
}

2.3.9 头删、尾删

  需要注意的是end()指向的是最后一个元素的下一个位置,因此删除时要先–end()。

void pop_back()
{
erase(--end());
}

void pop_front()
{
erase(begin());
}

3. list与vector的对比

在这里插入图片描述

4. 代码实现

4.1 list.h

#pragma once
#include<iostream>
#include"reverse_iterator.h"
using namespace std;

namespace WY
{
//在 list_node<T> 中加<T>可以理解为 list_node 是一个类,比如之前模拟实现的 vector,在使用时都会写成 vector<T>,目前就可以近似的这么理解

//在 list 中存放的都是一个一个的节点,而一个节点又包含数据域以及指针域,因此需要对节点进行封装,便于存储到 list 中
template <class T>
struct list_node
{
T _data;
struct list_node<T>* _next;
struct list_node<T>* _prev;

list_node(const T& x = T())
:_data(x)
,_next(nullptr)
,_prev(nullptr)
{}
};

// 因为 list 中迭代器的解引用以及 ++ 都无法像 vector 和 string 中那样使用,因此需要对迭代器进行封装实现这些功能
// 迭代器本质上也是在对节点进行运算,因此它的成员也是 Node*,参考 list<int>::iterator it = lt.begin(),lt.begin()返回的就是一个节点的地址
template <class T, class Ref, class Ptr>
struct __list_iterator
{
typedef list_node<T> Node;
typedef __list_iterator<T, Ref, Ptr> self;

Node* _node;

__list_iterator(Node* node)
:_node(node)
{}

Ref operator*()
{
return _node->_data;
}

Ptr operator->()
{
return &_node->_data;
}

self& operator++()
{
_node = _node->_next;
return *this; 
}

self& operator--()
{
_node = _node->_prev;
return *this;
}

self operator++(int)
{
self tmp(*this);
_node = _node->_next;
return tmp;
}

self operator--(int)
{
self tmp(*this);
_node = _node->_prev;
return tmp;
}

bool operator!=(const self& s)
{
return _node != s._node;
}

bool operator==(const self& s)
{
return _node == s._node; 
}
};

/*template <class t>
struct __list_const_iterator
{
typedef struct list_node<t> node;
typedef __list_const_iterator<t> self;

node* _node;

__list_const_iterator(node* node)
:_node(node)
{}

const t& operator*()
{
return _node->_data;
}

const t* operator->()
{
return &_node->_data;
}

self& operator++()
{
_node = _node->_next;
return *this;
}

self& operator--()
{
_node = _node->_prev;
return *this;
}

self operator++(int)
{
self tmp(*this);
_node = _node->_next;
return tmp;
}

self operator--(int)
{
self tmp(*this);
_node = _node->_prev;
return tmp;
}

bool operator!=(const self& s)
{
return _node != s._node;
}

bool operator==(const self& s)
{
return _node == s._node;
}
};*/


template<class T>
class list
{
// 只在类域里面使用,所以设置为私有,在 class 默认为私有,在 struct 中默认为公有
typedef struct list_node<T> Node;

public:

// 在类域外面也需要使用,因此要放到 public 里面
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, const T&, const T*> const_iterator;
//typedef __list_const_iterator<T> const_iterator;

typedef Reverse_Iterator<iterator, T&, T*> reverse_iterator;
typedef Reverse_Iterator<const_iterator, const T&, const T*> const_reverse_iterator;

reverse_iterator rbegin()
{
return --end();
}

reverse_iterator rend()
{
return end();
}

const_iterator begin()const
{
return _head->_next;
}

const_iterator end()const
{
return _head;
}

iterator begin()
{
return _head->_next;
}

iterator end()
{
return _head;
}


void empty_init()
{
_head = new Node;
_head->_next = _head;
_head->_prev = _head;
}

list()
{
empty_init();
}

~list()
{
clear();

delete _head;
_head = nullptr;
}

list(const list<T>& lt)
{
empty_init();

for (auto e : lt)
{
push_back(e);
}
}

lt2 = lt1
//list<T>& operator=(const list<T>& lt)
//{
//if (lt != *this)
//{
//clear();
//for (auto e : lt)
//{
//push_back(e);
//}
//}
//return *this;
//}

void swap(const list<T>& lt)
{
std::swap(_head, lt._head);
std::swap(_size, lt._size);
}

list<T>& operator=(list<T> lt)
{
swap(lt);
return *this;
}

void clear()
{
iterator it = begin();
while (it != end())
{
it = erase(it);
}
}

void push_back(const T& x)
{
//Node* newnode = new Node(x);
//Node* tail = _head->_prev;

//_head->_prev = newnode;
//newnode->_next = _head;

//tail->_next = newnode;
//newnode->_prev = tail;

insert(end(), x);
}

void push_front(const T& x)
{
insert(begin(), x);
}

void pop_back()
{
erase(--end());
}

void pop_front()
{
erase(begin());
}

iterator insert(iterator pos, const T& val)
{
Node* newnode = new Node(val);

Node* prev = pos._node->_prev;

// prev  newnode  pos._node
newnode->_next = pos._node;
pos._node->_prev = newnode;

newnode->_prev = prev;
prev->_next = newnode;
_size++;

return iterator(newnode);
}

iterator erase(iterator pos)
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* next = cur->_next;

prev->_next = next;
next ->_prev = prev;
_size--;

return iterator(next);
}

private:
Node* _head;
size_t _size;
}; 

void test_list1()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);

list<int>::iterator it = lt.begin();
while (it != lt.end())
{
cout << *it << " ";
++it;
}
cout << endl;

for (auto e : lt)
{
cout << e << " ";
}
cout << endl;
}

//void Print_list(const list<int>& lt)
//{
//list<int>::const_iterator it = lt.begin();
//while (it != lt.end())
//{
//cout << *it << " ";
//++it;
//}
//cout << endl;
//}

//template<typename T>
//void Print_list(const list<T>& lt)
//{
//// 加 typename 的原因:编译器在编译时只会对实例化的模板进行编译,而这里的 list<T> 并没有被实例化,参数里的 list<T> 在进行传参时会被实例化
//// 而函数体内的并没有进行实例化,所以在编译时编译器无法识别 const_iterator 是内嵌类型还是静态成员变量,所以在编译是会报错
//// 而加了 typename,会让编译器跳过这个检查阶段,我目前的理解是在用 lt.begin() 对 it 进行赋值时才会对前面的 list<T> 进行实例化(待查证)
//typename list<T>::const_iterator it = lt.begin();
//while (it != lt.end())
//{
//cout << *it << " ";
//++it;
//}
//cout << endl;
//}

template<typename Container>
void Print_container(const Container& con)
{
typename Container::const_iterator it = con.begin();
while (it != con.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}

void test_list2()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);

//Print_list(lt);
Print_container(lt);
}

void test_list3()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);

list<int>::reverse_iterator it = lt.rbegin();
while (it != lt.end())
{
cout << *it << " ";
++it;
}
cout << endl;

Print_container(lt);
}

void test_list4()
{
list<int> lt;
lt.push_back(1);
lt.push_back(2);
lt.push_back(3);
lt.push_back(4);
lt.push_back(5);

list<int>::iterator it = lt.begin();
while (it != lt.end())
{
cout << *it << " ";
it++;
}
cout << endl;

}
}

4.2 reverse_iterator.h

  这部分是反向迭代器的封装。

#pragma once

template<class iterator,class Ref,class Ptr>
class Reverse_Iterator
{
public:
typedef Reverse_Iterator Self;
Reverse_Iterator(iterator it)
:_it(it)
{}

Self& operator++()
{
--_it;
return *this;
}

bool operator!=(const Self& it)
{
return _it != it._it;
}

Ref operator*()
{
return *_it;
}

Ref operator->()
{
return _it.operator();
}

private:
iterator _it;
};

4.3 test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"list.h"

int main()
{
//WY::test_list1();
//WY::test_list2();
//WY::test_list3();
WY::test_list4();
return 0;
}

5.总结

  list有关迭代器的封装比较困难复杂,它这个封装一层套一层,所以较难理解,可能有的地方 我表达的不是很清楚,大家可以多加阅读以及结合相关部分的文章进理解。并且如果有难以理解的地方,可以私信我,我看到之后会帮助大家解决问题,希望能与大家共同进步。
  如果大家发现有什么错误的地方或者有什么问题,可以私信或者评论区指出喔。我会继续深入学习C++,希望能与大家共同进步,那么本期就到此结束,让我们下期再见!!觉得不错可以点个赞以示鼓励!!


原文地址:https://blog.csdn.net/qq_62321047/article/details/135657732

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!