【C++】list的使用和list的模拟实现和迭代器失效问题

目录

一、list 的简单介绍

二、list 的基本使用

🎉list的构造

🎉list iterator 的使用

🎉list capacity

🎉list element access

🎉list modifiers

🎉list operator 

三、list 的模拟实现

🌟模拟实现list

🎉前置operator++/operator--

🎉 后置operator++(int) / operator--(int)

🎉operator!=/operator== 

 🎉operator*()

 ​​🎉operator->()

 🎉迭代器iterator  

🎉迭代器const_iterator 

 迭代器的另一种写法:

🌟List相关接口函数的模拟实现 :

🎉insert()

🎉erase()

​编辑

🌟迭代器失效问题

 🎉尾删/头删/头插

🎉List()

🎉深拷贝List(const List& lt)

🎉~List()

🎉List& operator=()

🎉初始化initializer_list

四、list 和 vector 的对比

五、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来说这可能是一个重要的因素)

二、list 的基本使用

🎉list的构造

构造函数接口说明
list (size_type n, const value_type& val=value_type())构造的list中包含n个值为val的元素
list()构造空的list
list (const list& x)拷贝构造函数
list ( InputIterator first, InputIterator last)用 [ first , last ) 区间中的元素构造list
#include<iostream>
#include<list>using namespace std; int main()
{list<int> l1; //构造空的l1list<int> l2(4, 100); // 构造4个值为100的元素list<int> l3(l2.begin(), l2.end());  //用l2的[begin(),end())左闭右开区间构造l3list<int> l4(l3);//以数组为迭代区间构造l5int array[] = { 16,2,77,29 };list<int> l5(array, array + sizeof(array) / sizeof(int));//array  array+sizeof(4)//列表格式初始化C++11list<int> l6{ 1,2,3,4,5 };//用迭代器方式打印l5中的元素list<int>::iterator it = l5.begin();while (it != l5.end()){cout << *it << " ";++it;}cout << endl;//C++范围for的方式遍历for (auto& e : l5){cout << e << " ";}cout << endl;return 0;
}

🎉list iterator 的使用

 

此处,可以暂时将迭代器理解成一个指针,该指针指向list中的某个结点。

函数声明接口说明
begin() + end()返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器
rbegin() + rend()返回第一个元素的 reverse_iterator, 即end位置,返回最后一个元素下一个位置的 reverse_iterator,即begin位置

//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;
}
#include<iostream>
#include<list>using namespace std;   int main()
{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;return 0;
}

【注意】

1、begin与end为正向迭代器,对迭代器执行++操作,迭代器向后移动

2、rbegin(end) 与 rend(begin)为反向迭代器,对迭代器执行++操作,迭代器向前移动

🎉list capacity

 

函数说明接口说明
empty()检测list是否为空,是返回ture,否则返回false
size()返回list中有效节点的个数
max_size()返回列表容器可以容纳的最大元素数
#include<iostream>
#include<list>using namespace std;int main ()
{std::list<int> mylist;int sum (0);for (int i=1;i<=10;++i) mylist.push_back(i);while (!mylist.empty()){sum += mylist.front();mylist.pop_front();}std::cout << "total: " << sum << '\n';return 0;
}

 

#include<iostream>
#include<list>using namespace std;int main()
{std::list<int> myints;std::cout << "0. size: " << myints.size() << '\n';for (int i = 0; i < 10; i++){myints.push_back(i);}std::cout << "1. size: " << myints.size() << '\n';myints.insert(myints.begin(), 10, 100);for (list<int>::const_iterator it = myints.begin(); it != myints.end(); ++it){cout << *it << " ";}cout << endl;std::cout << "2. size: " << myints.size() << '\n';myints.pop_back();std::cout << "3. size: " << myints.size() << '\n';return 0;
}

🎉list element access

函数声明接口说明
front返回list的第一个节点中值的引用
back返回list的最后一个节点中值的引用

🎉list modifiers

 

函数声明接口说明
push_front()在list首元素前插入值为val的元素
pop_front()删除list中第一个元素
push_back()在list的尾部插入值为val的元素
pop_back()删除list中最后一个元素
#include<iostream>
#include<list>using namespace std;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;}int main()
{int array[] = { 1,2,3,4,5,6,7,8,9 };list<int> L(array, array + sizeof(array) / sizeof(array[0]));//尾插  头插L.push_back(4);L.push_front(0);Printlist(L);//尾删  头删L.pop_back();L.pop_front();Printlist(L);return 0;
}

 

函数声明接口说明
insert在list position 位置中插入值为val的元素
erase删除list position 位置的元素
#include<iostream>
#include<list>
#include<vector>using namespace std;
int main()
{int array[] = { 1,2,3 };list<int> L(array, array + sizeof(array) / sizeof(array[0]));//获取链表中的第二个结点//list<int>::iterator it = ++L.begin();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);return 0;
}

 

函数声明接口说明
swap交换两个list中的元素
resize调整容器的大小,使其包含n个元素
clear清空list中的有效元素
#include<iostream>
#include<list>using namespace std;int main()
{
// 用数组来构造listint array[] = { 1,2,3 };list<int> L1(array, array + sizeof(array) / sizeof(array[0]));Printlist(L1);// 交换l1和l2中的元素list<int> L2;L1.swap(L2);Printlist(L1);Printlist(L2);// 将l2中的元素清空L2.clear();cout << L2.size() << endl;return 0;
}

 

🎉list operator 

(1)将元素从列表转移到列表
(2)将元素从x转移到容器中,并将其插入到指定位置
(3)有效地将这些元素插入容器中,并将其从x中删除,从而改变了两者的大小容器。该操作不涉及任何元素的构造或销毁,无论x是左值还是右值,或者值类型是否支持移动构造,它们都会被转移。

第一个版本(1)将x的所有元素转移到容器中。
第二个版本(2)只将i指向的元素从x转移到容器中
第三个版本(3)将范围[first,last)从x转移到容器中。

函数声明接口函数
splice将元素从列表转移到列表(剪切
merge合并已排序列表
#include<iostream>
#include<list>using namespace std;int main()
{std::list<int> mylist1, mylist2;std::list<int>::iterator it;for (int i = 1; i <= 4; ++i)mylist1.push_back(i);        //mylist1: 1 2 3 4for (int i = 1; i <= 3; ++i)mylist2.push_back(i * 10);   //mylist2: 10 20 30it = mylist1.begin();++it;                        //position to 2mylist1.splice(it, mylist2);   //mylist1:  1 10 20 30 2 3 4 // mylist2(empty)return 0;
}

三、list 的模拟实现

🌟模拟实现list

list的底层是双向链表结构,双向链表中每个元素存储在互不相关的独立节点中,在节点中通过指针指向其前一个元素和后一个元素,因此模拟实现时,要对双链表的节点进行封装,list对元素进行访问时,不能用普通的迭代器进行访问下一个元素,因为双链表在物理上是不连续的,因此又要对双链表的迭代器进行封装。

这里我们对list的模拟实现放在一个头文件进行实现,我们要写在一个命名空间里面,为了避免命名冲突或名字污染,对(带头双向循环链表)双链表的节点进行封装

// List.h
namespace xlf
{//双链表的定义//类模板template<class T>struct ListNode{// ListNode<T>*是一个类型 例:int*ListNode<T>* _prev; //指向前一个节点的指针ListNode<T>* _next;//指向后一个节点的指针T _data;//节点的数据//构造ListNode(const T& data):_prev(nullptr),_next(nullptr),_data(data){}};}

•  为什么用 struct 而不用 class 来创建类呢?

  struct  不受访问限定符的限制,class 使用受限,如果使用class,则要把成员函数和成员变量全部设为公有,这里的ListNode节点要经常使用。

template 定义的模板参数,只能供当前类或当前函数使用

对List进行封装:

	template<class T>class List{typedef ListNode<T> Node; //为类型取别名public://节点初始化//双链表有哨兵位List(){_head = new Node(T());//用匿名对象进行初始化_head->_prev = _head;_head->_next = _head;}//尾插void push_back(const T& x){//创建新节点Node* newnode = new Node(x);//找尾节点Node* tail = _head->_prev;//连接newnode->_prev = tail;//1tail->_next = newnode;//2newnode->_next = _head;//3_head->_prev = newnode;//4}private:Node* _head;};

 哨兵位如何初始化?

此时,当我们对链表的数据进行访问/修改时,我们不能用普通的迭代器进行访问,链表在物理空间上是不连续的,因此我们需要对迭代器进行封装

	//链表迭代器template<class T>struct ListIterator{typedef ListNode<T> Node;//给节点取别名typedef ListIterator<T> Self;//給迭代器取别名Node* _node;//节点public://构造函数ListIterator(Node* node):_node(node){}//对自定义进行运算符的重载,可控制迭代器的行为};

现在我们来实现一般所需的重载运算符:

   • 对自定义类型运算符的重载,可控制迭代器的行为

🎉前置operator++/operator--

Self& operator++()//出了当前作用域不销毁,用传引用返回{_node = _node->_next;return *this;}Self& operator--()//出了当前作用域不销毁,用传引用返回{_node = _node->_prev;return *this;}

      •  传引用返回,是因为出了当前作用域,*this这个值不销毁

      •  _node=_node->_next  表示这个节点的下一个节点

       •  _node=_node->_prev  表示这个节点的前一个节点

🎉 后置operator++(int) / operator--(int)

		Self operator++(int)//出了作用域这个值会销毁,用传值返回{Node* temp(*this);    // d++ :返回的是++之前的值// 所以要先保留++之前的值_node = _node->_next;return temp;}Self operator--(int)//出了作用域这个值会销毁,用传值返回{Node* temp(*this);    // d-- :返回的是--之前的值// 所以要先保留--之前的值_node = _node->_prev;return temp;}

      • 前置++和后置++的区别:(返回值不一样)

           ++d :返回++之后的值

           d++:返回++之前的值

      •  Node* temp(*this)   表示先保留++/-- 之前的值,当做返回值

      •用传值返回,是因为 temp 出了当前作用域后,就会被销毁

🎉operator!=/operator== 

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

 🎉operator*()

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

 为什么重载 operator*() 呢?

 • 重载operator*(),是为了可以获取到节点里面的数据。

测试例子:

		List<int>::iterator it = L.begin();while (it != L.end()){cout << *it << " ";//*it 解引用要的是数值,不是节点,所以运算符重载了operator*()++it;}cout << endl;

 ​​🎉operator->()

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

 为什么重载operator->()呢?

看这个例子:

	struct Pos{int _row;int _col;Pos( int row = 0,int col = 0):_row(row),_col(col){}};void test_list3(){List<Pos> L;L.push_back(Pos(100, 100));L.push_back(Pos(200, 200));L.push_back(Pos(300, 300));List<Pos>::iterator it = L.begin();while (it !=L. end()){cout << it->_row << ":" << it->_col << endl;//cout << it.operator->()->_row << ":" << it.operator->()->_col << endl;++it;}cout << endl;}

 • 我们访问 int类型,可以用int*,如果我们访问 Pos* 这个自定义类型数据该如何访问?重载运算符,在结构体、类(公有),想访问成员,模拟这个行为,可以用 -> 来进行访问。

• cout << it->_row << ":" << it->_col << endl     实际为:

  cout << it.operator->()->_row << ":" << it.operator->()->_col << endl;

第一个->:运算符重载的调用;

第二个->:原生指针

 🎉迭代器iterator  

此时就可以在List类里面实现部分迭代器:

	template<class T>class List{typedef ListNode<T> Node; //为类型取别名public:typedef ListIterator<T> iterator;iterator begin(){iterator it(_head->_next);return it;}iterator end(){iterator it(_head);return it;}}

测试迭代器: 

	void test_list1(){List<int> L;//实例化就报错L.push_back(1);L.push_back(2);L.push_back(3);L.push_back(4);List<int>::iterator it = L.begin();while (it != L.end()){*it += 10; // *it 解引用,返回的是这个节点的数据// 此时可以修改这个节点数据的内容cout << *it << " ";//*it 解引用要的是数值,不是节点,所以运算符重载了operator*()++it;}cout << endl;for (auto& e : L){cout << e << " ";}cout << endl;}

🎉迭代器const_iterator 

如何做到自己能修改,指向的内容不能修改?

迭代器只能控制,不能修改的核心行为是 operator*()operator->(),就是解引用时,要修改的东西。

	// const_iterator//链表迭代器template<class T>struct ListConstIterator{typedef ListNode<T> Node;//给节点取别名typedef ListConstIterator<T> Self;//給迭代器取别名Node* _node;//节点public://构造函数ListConstIterator(Node* node):_node(node){}//对自定义进行运算符的重载,可控制迭代器的行为Self& operator++(){_node = _node->_next;return *this;}Self& operator--(){_node = _node->_prev;return *this;}Self operator++(int){Node* temp(*this);_node = _node->_next;return temp;}Self operator--(int){Node* temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& it){return _node != it._node;}bool operator==(const Self& it){return _node == it._node;}const T& operator*(){return _node->_data;}const T* operator->(){return &_node->_data;}};

• 实现与iterator()相似,区别就在于operator*()operator->()  这两个运算符重载改为const,

  即: const T& operator*()const T* operator->() 

const iterator const  迭代器不能是普通迭代器前面加 const修饰

  const迭代器目的:本身可以修改,指向的内容不能修改

  例: const T* pp本身可以修改,*p不可以修改

代码测试: 

	void Func(const List<int>& lt){List<int>::const_iterator it = lt.begin();while (it!=lt.end()){//*it += 10; //const迭代器 指向的内容不能改变cout << *it << " ";//可读++it;//可遍历}cout << endl;}

 迭代器的另一种写法:

通过模板,给不同模板参数,让编译器帮我们写两个类(实例化)。

//迭代器的第二种写法:
//template 定义的模板参数,只能供当前类或当前函数使用//链表迭代器template<class T, class Ref, class Ptr>struct ListIterator{typedef ListNode<T> Node;//给节点取别名typedef ListIterator<T, Ref, Ptr> Self;//給迭代器取别名Node* _node;//节点public://构造函数ListIterator(Node* node):_node(node){}//对自定义进行运算符的重载,可控制迭代器的行为Self& operator++(){_node = _node->_next;return *this;}Self& operator--(){_node = _node->_prev;return *this;}Self operator++(int){Node* temp(*this);_node = _node->_next;return temp;}Self operator--(int){Node* temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& it){return _node != it._node;}bool operator==(const Self& it){return _node == it._node;}Ref operator*(){return _node->_data;}Ptr operator->(){return &_node->_data;}};

 • template <class T , class Ref , class Ptr>  通过模板给不同模板参数;

•  typedef ListIterator<T, Ref, Ptr> Self;    typedef时也要做相应的修改,此时表示当传入的 RefPtr 为常量时, Ref Ptr就会替代为常量;当传入的 Ref 和 Ptr 为非常量时, RefPtr就会替代为非常量;

• 改变 operator*() 的返回值类型从 T&   修改为 Ref ,

  改变 operator->() 的返回值类型从 T*   修改为 Ptr  ,

  这时返回值的类型看传给 Ref / Ptr 是什么 ;

•此时 List类 中修改

typedef ListIterator<T> iterator  —>   typedef ListIterator<T , T&, T*> iterator;
typedef ListConstIterator<T> const_iterator  —>   typedef ListIterator<T, const T&, const T*> const_iterator;

🌟List相关接口函数的模拟实现 :

🎉insert()

		//插入(在pos之前插入)iterator insert(iterator pos, const T& x){//找到Pos位置的节点Node* cur = pos._node;//开一个新节点Node* newnode = new Node(x);//找pos的前一个节点Node* prev = cur->_prev;//连接  prev  newnode curprev->_next = newnode;newnode->_prev = prev;newnode->_next = cur;cur->_prev = newnode;return iterator(newnode);}

 

🎉erase()

		iterator erase(iterator pos){//防止删掉哨兵位// pos end() 都是迭代器,_head是指针,所以不用assert(pos != end());//找到posNode* cur = pos._node;//pos的前一个节点Node* prev = cur->_prev;//pos的后一个节点Node* next = cur->_next;//连接 prev    nextprev->_next = next;next->_prev = prev;//删除节点delete cur;return iterator(next);}

🌟迭代器失效问题

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

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

 🎉尾删/头删/头插

		//尾删void pop_back(){erase(--end());}//头删void pop_front(){erase(begin());}//头插void push_front(const T& x){insert(begin(), x);}

直接复用前面模拟实现过的函数。 

🎉List()

		//节点初始化//双链表有哨兵位List(){_head = new Node(T());//创建一个T()类型的节点_head->_prev = _head;//节点前后都指向自己_head->_next = _head;}

因为下面的几个函数实现都需要初始化,所以把初始化写成一个函数。

		//哨兵位头节点void empty_init(){_head = new Node(T());_head->_next = _head;_head->_prev = _head;}//节点初始化//双链表有哨兵位List(){//_head = new Node(T());//创建一个T()类型的节点//_head->_prev = _head;//节点前后都指向自己//_head->_next = _head;empty_init();}

🎉深拷贝List(const List<T>& lt)

当不实现深拷贝时,系统会自动调用默认构造,此时就是浅拷贝,会出现一些问题:

此时,L1的更新会影响L2的数据,底层实际是L1和L2指向同一块空间,因此需要手动写拷贝构造。

		//深拷贝//lt2(lt1)List(const List<T>& lt){//先把原来list里面的数据初始化empty_init();//把lt1里面的数据一个一个尾插到lt2for (const auto& e : lt){push_back(e);}}

 此时,L1数据的更新不会影响L2:

🎉~List()

在写析构时,我们先要把list里面的数据全部清除,然后再删除头节点的指针并置空。

		~List(){clear();delete _head;_head = nullptr;}void clear(){auto it = begin();while (it != end()){it = erase(it);}}

🎉List<T>& operator=()

		//传值传参//lt1=lt3// 交换两个list的数据后,这两个list还在,所以用传引用返回List<T>& operator=(List<T> lt)//lt3出了当前作用域不销毁,所以用传引用返回{swap(_head, lt._head);//直接用库里面的函数return * this;}

🎉初始化initializer_list

		List(initializer_list<T> il){empty_init();for (const auto& e : il){push_back(e);}}

四、list 和 vector 的对比

vector与list都是STL中非常重要的序列式容器,由于两个容器的底层结构不同,导致其特性以及应用场景不同,其主要不同如下:

vectorlist
底层结构动态顺序表,一段连续空间带头结点的双向循环链表
随机访问支持随机访问,访问某个元素效率O(1)不支持随机访问,访问某个元素效率O(N)
插入和删除任意位置插入和删除效率低,需要搬移元素,时间复杂度为O(N),插入时有空能增容,增容:开辟新空间,拷贝元素,释放旧空间,导致效率更低任意位置插入和删除效率高,不需要搬移元素,时间复杂度为O(1)
空间利用率底层为连续空间,不容易造成内存碎片,空间利用率高,缓存利用率高底层节点动态开辟,小节点容易造成内存碎片,空间利用率低,缓存利用率低
迭代器原生态指针对原生态指针(节点指针)进行封装
迭代器失效在插入元素时,要给所有的迭代器进行赋值,因为插入元素可能会导致重新扩容,致使原来迭代器失效,删除时,当前迭代器需要重新赋值否则会失效插入元素不会导致迭代器失效,删除元素时,只会导致当前迭代器失效,其他迭代器不受影响
使用场景需要高效存储,支持随机访问,不关心插入删除效率大量插入和删除操作,不关心随机访问

五、list模拟实现的完整代码

#pragma once
#include<iostream>
#include<assert.h>using namespace std;namespace xlf
{//双链表的定义//类模板template<class T>struct ListNode{// ListNode<T>*是一个类型 例:int*ListNode<T>* _prev; ListNode<T>* _next;T _data;//构造ListNode(const T& data):_prev(nullptr),_next(nullptr),_data(data){}};//迭代器的第一种写法:链表迭代器//template<class T>//struct ListIterator//{//	typedef ListNode<T> Node;//给节点取别名//	typedef ListIterator<T> Self;//給迭代器取别名//	Node* _node;//节点//public://	//构造函数//	ListIterator(Node* node)//		:_node(node)//	{}//	//对自定义进行运算符的重载,可控制迭代器的行为//	Self& operator++()//	{//		_node = _node->_next;//		return *this;//	}//	Self& operator--()//	{//		_node = _node->_prev;//		return *this;//	}//	Self operator++(int)//	{//		Node* temp(*this);//		_node = _node->_next;//		return temp;//	}//	Self operator--(int)//	{//		Node* temp(*this);//		_node = _node->_prev;//		return temp;//	}//	bool operator!=(const Self& it)//	{//		return _node != it._node;//	}//	bool operator==(const Self& it)//	{//		return _node == it._node;//	}//	T& operator*()//	{//		return _node->_data;//	}//	T* operator->()//	{//		return &_node->_data;//	}//};const_iterator链表迭代器//template<class T>//struct ListConstIterator//{//	typedef ListNode<T> Node;//给节点取别名//	typedef ListConstIterator<T> Self;//給迭代器取别名//	Node* _node;//节点//public://	//构造函数//	ListConstIterator(Node* node)//		:_node(node)//	{}//	//对自定义进行运算符的重载,可控制迭代器的行为//	Self& operator++()//	{//		_node = _node->_next;//		return *this;//	}//	Self& operator--()//	{//		_node = _node->_prev;//		return *this;//	}//	Self operator++(int)//	{//		Node* temp(*this);//		_node = _node->_next;//		return temp;//	}//	Self operator--(int)//	{//		Node* temp(*this);//		_node = _node->_prev;//		return temp;//	}//	bool operator!=(const Self& it)//	{//		return _node != it._node;//	}//	bool operator==(const Self& it)//	{//		return _node == it._node;//	}//	const T& operator*()//	{//		return _node->_data;//	}//	const T* operator->()//	{//		return &_node->_data;//	}//};//迭代器的第二种写法:
//template 定义的模板参数,只能供当前类或当前函数使用//链表迭代器template<class T, class Ref, class Ptr>struct ListIterator{typedef ListNode<T> Node;//给节点取别名typedef ListIterator<T, Ref, Ptr> Self;//給迭代器取别名Node* _node;//节点public://构造函数ListIterator(Node* node):_node(node){}//对自定义进行运算符的重载,可控制迭代器的行为Self& operator++(){_node = _node->_next;return *this;}Self& operator--(){_node = _node->_prev;return *this;}Self operator++(int){Node* temp(*this);_node = _node->_next;return temp;}Self operator--(int){Node* temp(*this);_node = _node->_prev;return temp;}bool operator!=(const Self& it){return _node != it._node;}bool operator==(const Self& it){return _node == it._node;}Ref operator*(){return _node->_data;}Ptr operator->(){return &_node->_data;}};//链表实现template<class T>class List{typedef ListNode<T> Node; //为类型取别名public:迭代器的第一种写法://typedef ListIterator<T> iterator;//typedef ListConstIterator<T> const_iterator;//迭代器的第二种写法:typedef ListIterator<T, T&, T*> iterator;typedef ListIterator<T, const T&, const T*> const_iterator;iterator begin(){/*iterator it(_head->_next);return it;*/return iterator(_head->_next);//匿名对象}iterator end(){/*iterator it(_head->_prev);return it;*/return iterator(_head);//匿名对象}const_iterator begin() const{/*const_iterator it(_head->_next);return it;*/return const_iterator(_head->_next);//匿名对象}const_iterator end() const{/*const_iterator it(_head);return it;*/return const_iterator(_head);}//尾插void push_back(const T& x){//创建新节点Node* newnode = new Node(x);//找尾节点Node* tail = _head->_prev;//连接 tail newnode _headtail->_next = newnode;newnode->_prev = tail;newnode->_next = _head;_head->_prev = newnode;//insert(end(), x);}//插入(在pos之前插入)iterator insert(iterator pos, const T& x){//找到Pos位置的节点Node* cur = pos._node;//开一个新节点Node* newnode = new Node(x);//找pos的前一个节点Node* prev = cur->_prev;//连接  prev  newnode curprev->_next = newnode;newnode->_prev = prev;newnode->_next = cur;cur->_prev = newnode;return iterator(newnode);}iterator erase(iterator pos){//防止删掉哨兵位// pos end() 都是迭代器,_head是指针,所以不用assert(pos != end());//找到posNode* cur = pos._node;//pos的前一个节点Node* prev = cur->_prev;//pos的后一个节点Node* next = cur->_next;//连接 prev    nextprev->_next = next;next->_prev = prev;//删除节点delete cur;return iterator(next);}//尾删void pop_back(){erase(--end());}//头删void pop_front(){erase(begin());}//头插void push_front(const T& x){insert(begin(), x);}//哨兵位头节点void empty_init(){_head = new Node(T());_head->_prev = _head;_head->_next = _head;}//节点初始化//双链表有哨兵位List(){//_head = new Node(T());//创建一个T()类型的节点//_head->_prev = _head;//节点前后都指向自己//_head->_next = _head;empty_init();}//深拷贝//lt2(lt1)List(const List<T>& lt){//先把原来list里面的数据初始化empty_init();//把lt1里面的数据一个一个尾插到lt2for (const auto& e : lt){push_back(e);}}~List(){clear();//清空list里面的数据delete _head;//释放头节点_head = nullptr;//头节点指针置为空,防止出现野指针}void clear(){auto it = begin();while (it != end()){it = erase(it);}}//传值传参//lt1=lt3// 交换两个list的数据后,这两个list还在,所以用传引用返回List<T>& operator=(List<T> lt)//lt3出了当前作用域不销毁,所以用传引用返回{swap(_head, lt._head);//直接用库里面的函数return * this;}List(initializer_list<T> il){empty_init();for (const auto& e : il){push_back(e);}}private:Node* _head;};//按需实例化void test_list1(){List<int> L;//实例化就报错L.push_back(1);L.push_back(2);L.push_back(3);L.push_back(4);List<int>::iterator it = L.begin();while (it != L.end()){*it += 10; // *it 解引用,返回的是这个节点的数据// 此时可以修改这个节点数据的内容cout << *it << " ";//*it 解引用要的是数值,不是节点,所以运算符重载了operator*()++it;}cout << endl;for (auto& e : L){cout << e << " ";}cout << endl;}struct Pos{int _row;int _col;Pos( int row = 0,int col = 0):_row(row),_col(col){}};void test_list3(){List<Pos> L;L.push_back(Pos(100, 100));L.push_back(Pos(200, 200));L.push_back(Pos(300, 300));List<Pos>::iterator it = L.begin();while (it !=L. end()){cout << it->_row << ":" << it->_col << endl;++it;}cout << endl;}void Func(const List<int>& lt){//List<int>::const_iterator it = lt.begin();//while (it!=lt.end())//{//	//*it += 10; //const迭代器 指向的内容不能改变//	cout << *it << " ";//可读//	++it;//可遍历//}//cout << endl;List<int>::const_iterator it = lt.begin();while (it != lt.end()){//*it += 10;//const迭代器 指向的内容不能修改cout << *it << " ";//可读++it;//可遍历}cout << endl;}void test_List3(){List<int> L;L.push_back(1);L.push_back(2);L.push_back(3);L.push_back(4);L.push_back(5);Func(L);L.push_front(10);L.push_front(20);L.push_front(30);Func(L);L.pop_front();L.pop_front();Func(L);L.pop_back();L.pop_back();L.pop_back();/*L.pop_back();L.pop_back();L.pop_back();L.pop_back();L.pop_back();L.pop_back();*/Func(L);}void test_List4(){List<int> L1;L1.push_back(1);L1.push_back(2);L1.push_back(3);L1.push_back(4);L1.push_back(5);Func(L1);List<int> L2(L1);L1.push_back(6);Func(L2);Func(L1);List<int> L3;L3.push_back(1);L3.push_back(2);L3.push_back(3);L1 = L3;Func(L1);Func(L3);}void test_List5(){List<int> L1 = { 1,2,3,4,5,6 };Func(L1);}}

如若对你有帮助,记得点赞、收藏、关注哦!

若有误,望各位,在评论区留言或者私信我 指点迷津!!!谢谢^ ^ ~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/51782.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【一个简单的整数问题】

问题 TLE代码 #include <bits/stdc.h> using namespace std; const int N 1e510; int b[N]; void add(int l, int r, int d) {b[r1] - d;b[l] d; } int query(int x) {int retval 0;for(int i 1; i < x; i){retval b[i];}return retval; } int main() {int n, m…

C++基础面试题 | 介绍C++中三种智能指针的使用场景?

月落乌啼霜满天&#xff0c;江枫渔火对愁眠。 - 《枫桥夜泊 / 夜泊枫江》(张继) 回答重点 在C中的智能指针利用RAII实现内存分配的管理&#xff0c;避免内存泄漏和其他与动态内存分配相关的问题。C11中提供了三种主要的智能指针&#xff1a;std::unique_ptr、std::shared_ptr和…

【软件测试】测试分类

系列文章目录 第一章 【软件测试】常见的开发模型和测试模型 第二章 【软件测试】bug以及测试用例的设计方法 文章目录 系列文章目录前言一、按照测试目标进行分类二、按照执行方式分类三、按照测试方法四、按照测试阶段分类五、按照实施组织分类总结 前言 在前文中简单了解了…

【编程底层思考】线程阻塞时一定会释放cpu吗

线程阻塞时是否释放CPU取决于阻塞的原因和操作系统的行为。以下是一些具体情况&#xff1a; 1. 阻塞等待资源&#xff1a;当线程因为等待某个资源&#xff08;如锁、信号量、条件变量等&#xff09;而阻塞时&#xff0c;它通常会释放CPU&#xff0c;以便其他线程可以运行。在这…

MATLAB绘图基础4:MATLAB函数

参考书&#xff1a;《 M A T L A B {\rm MATLAB} MATLAB与学术图表绘制》(关东升)。 4.函数 4.1 定义函数 创建新函数文件 % 1.函数文件&#xff1a; % 1.1 函数文件包含一个或多个函数的定义; % 1.2 函数文件包含函数头,用于指定函数名称和输入参数,如:function output func…

掌握测试的艺术:深入探索Python的pytest库

文章目录 **掌握测试的艺术&#xff1a;深入探索Python的pytest库**背景&#xff1a;为什么选择pytest&#xff1f;pytest是什么&#xff1f;如何安装pytest&#xff1f;5个简单的库函数使用方法1. pytest.main()2. pytest.skip()3. pytest.mark.parametrize()4. pytest.raises…

python 地理抠图

python 地理抠图 在Python中进行地理抠图&#xff0c;可以使用geopandas库&#xff0c;它是基于pandas的地理空间数据处理库。以下是一个简单的例子&#xff0c;展示如何根据一个多边形区域来抠出该区域内的地理数据。 首先&#xff0c;安装必要的库&#xff08;如果尚未安装&…

力扣1425.带限制的子序列和

力扣1425.带限制的子序列和 单调队列优化dp f[i] 表示在数组的前 i 个数中进行选择&#xff0c;并且恰好选择了第 i 个数&#xff0c;可以得到的最大和状态转移&#xff1a;f[i] max(max(f[j]) , 0) nums[i];单调队列优化&#xff1a;储存前K个f[i]&#xff0c;并且单调&…

Go 语言生产服务故障案例精析

大多数 Go 开发者都停留在简单的增删改查层面,对 Go 语言本身掌握程度不够,对常用依赖或者开源组件掌握不够,在开发项目过程中总会不经意间引入一些千奇百怪的问题,并且在遇到线上问题时往往束手无策。下面列举一些线上问题以及相应的解决思路,希望大家能从这些问题中吸取…

Debian 安装 OpenSSH 服务器

Debian 安装 OpenSSH 服务器 先查看装了没安装 OpenSSH 服务器软件包启动 SSH 服务&#xff1a;查看服务状态修改 SSH 配置&#xff08;测试机可跳过&#xff09;连接测试文件收发 lrzsz 先查看装了没 apt-cache policy openssh-server安装 OpenSSH 服务器软件包 更新软件包列…

Notion 详细使用基础教程

1. 引言 什么是Notion? Notion是一款集笔记、任务管理、知识库和协作工具于一体的生产力应用。它被广泛用于个人和团队的日常工作和学习中。与传统的生产力工具不同&#xff0c;Notion提供了高度的自定义功能&#xff0c;允许用户根据自己的需求创建独特的工作流&#xff0c;…

(1)冒泡排序和其优化

一 冒泡排序 1.1 冒泡排序概念 冒泡排序&#xff08;Bubble Sort&#xff09;是一种交换排序&#xff0c;基本思想是&#xff1a;两两比较相邻记录的关键字&#xff0c;如果反序则交换&#xff0c;直到没有反序记录位置。 假设要对无序数列{2,3,4,5,6,7,8,1}排序&#xff1a;…

VastBase——执行计划

一、SQL的执行过程 1.词法分析 从查询语句中识别出系统支持的关键字、标识符、运算符、终结符等&#xff0c;确定每个词固有的特性。 以如下这个查询为例&#xff1a; select name from test_0717 where id > 1; 该SQL语句可以划分的关键字、标识符、运算符、常量等…

深入理解linux内核hung_task机制,最全!原创!

背景 最近的一个项目里&#xff0c;发生的问题近乎多半都是hangdetect的问题&#xff0c;之前一直对这种问题总是一知半解&#xff0c;发现主要是因为对此种维测方案(hangdetect/hangtask/watchdog/hungdetect)的理解不够深刻&#xff0c;而更深层次的原因是对于内核的各种机(…

vue3 setup基本使用

1. 基本概念 在 Vue 3 中&#xff0c;setup 函数是在组件创建之前调用的&#xff0c;用于初始化组件的响应式数据、计算属性、方法等。setup 函数返回的对象会作为组件的上下文提供给模板&#xff0c;模板中可以直接访问返回的属性和方法。 <template><div><p…

【python学习】-在条件分支结构中错误使用or导致其他条件分支的代码跳过并不执行

在条件分支结构中错误使用or导致其他条件分支的代码跳过并不执行 bug的来源背景代码目标第一版代码第二版代码第三版代码 问题总结后语 bug的来源背景 由于课题更换的原因&#xff0c;最近去做实验搬砖工了&#xff0c;所以大半年没有写代码&#xff0c;这两天开始处理一些代码…

使用CMake组织构建QT项目

文章目录 定位Qt安装路径查找QT包设置自动MOC、UIC和RCC包含和链接Qt库处理资源文件调整编译器设置处理UI文件多平台支持高级编译选项在使用CMake来组织和构建Qt项目时,需要注意一系列的细节以确保项目的顺利编译和运行。这些细节涉及确保Qt和CMake之间的兼容性、处理UI文件和…

HTML详解

1. 文档结构标签 <!DOCTYPE html>&#xff1a;声明文档类型&#xff0c;告诉浏览器这是一个HTML5文档。<html>&#xff1a;HTML文档的根元素&#xff0c;包含整个HTML文档。<head>&#xff1a;包含文档的元数据&#xff08;metadata&#xff09;&#xff0c…

计算多图的等价无向图的邻接链表表示

计算多图的等价无向图的邻接链表表示 摘要:一、引言二、算法思路三、伪代码实现四、C代码实现五、算法分析六、结论摘要: 在图论中,多图(Multigraph)是一种允许边重复以及存在自循环边(即一个顶点到其自身的边)的图。给定一个多图的邻接链表表示,本文旨在探讨如何构造…

Git 忽略已经提交的文件

对于未提交过的文件直接用ignore文件即可,不再赘述 对于已经提交过的文件,但是实际上不需要的,可以用git rm --cached命令 比如下图这个 .vsconfig被我误提交了或者忘了在ignore里添加了 但是我实际上不想要这个文件,那么在项目根目录打开git bash ,输入 git rm --cached .vsc…