【C++ STL】 list 模拟实现

简介: 本篇将学习 list 的模拟实现,它的主要难点在与迭代器的模拟。

📍前言

本篇将学习 list 的模拟实现,它的主要难点在与迭代器的模拟。


🕺作者: 迷茫的启明星

专栏:《C++初阶》

😘欢迎关注:👍点赞🙌收藏✍️留言


🏇码字不易,你的👍点赞🙌收藏❤️关注对我真的很重要,有问题可在评论区提出,感谢阅读!!!


持续更新中~


🌈STL之list的模拟实现

🎈list_node节点的定义

这里需要使用结构体

在这里需要使用模板,因为数据类型是不确定的

双向链表的结构包括:两个指针和数据

我们在定义节点时还需要初始化

template<class T>
struct list_node
{
    T _data;
    list_node<T>* _next;
    list_node<T>* _prev;
  //初始化
    list_node(const T& val = T())
        //为什么传引用?
        //传引用减少拷贝
        //初始化的值是T的默认构造函数,不能传0
        //T可能是string类型或其他类型
    :_data(val)
    ,_next(nullptr)
    ,_prev(nullptr)
    {}
};


🎈iterator迭代器

迭代器可以理解成指针,但是它比指针复杂多了,指针无外乎地址,而迭代器则是不是指针,却要让它实现指针的功能:++、–、*等操作


🕯️构造函数

我们构造好了一个_node,但是没有给他赋值,就等着外面传过来一个node,把node给给里面的_node即可。


__list_iterator(Node* node)

   :_node(node)

   {}


🕯️*it

我们把迭代器比作指针,方便理解,这个函数就是对“指针”解引用,拿到它的值。注意结果返回引用,减少拷贝


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


🕯️->

拿到节点的值的地址,因为返回的是一个地址,所以要用指针接收。结果返回一个指针。


Ptr operator->()
{ 
   return &(operator*());
}

🕯️it++/++it

为了实现类似指针的效果,迭代器前置++和后置++分别就要返回没改变的值和改变了的值。


++it

迭代器向后走一步,返回加过的值(还是一个迭代器)

it++

迭代器向后走一步,返回没加过的值(还是一个迭代器)


//++it
iterator& operator++()
{
   _node = _node->_next;
   return *this;
}
// it++
iterator operator++(int)
{
   iterator tmp(*this);//保存原来的值
   _node = _node->_next;
   return tmp;
}


🕯️it–/–it

原因与上同

// --it
iterator& operator--()
{
   _node = _node->_prev;
   return *this;
}
// it--
iterator operator--(int)
{
   iterator tmp(*this);
   _node = _node->_prev;
   return tmp;
}


🕯️!= / ==

仅需判断里面的this是否一样即可


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

🎈list类

🕯️begin()/end()

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


🕯️const_begin()/const_end()

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


🕯️构造函数

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

🕯️insert函数

双向链表的插入,是不是非常简单呢?只需要将新的节点的指针与插入位置前后指针相连即可。

iterator insert(iterator pos, const T& x)
{
   Node* cur = pos._node;
   Node* prev = cur->_prev;
   Node* newnode = new Node(x);
   prev->_next = newnode;
   newnode->_prev = prev;
   newnode->_next = cur;
   cur->_prev = newnode;
   return iterator(newnode);


🕯️erase函数

与Insert函数一样,把需要删除的节点的前后节点绑在一起就完成了。

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 iterator(next);
}


🕯️push_back函数

它有两种方式,既可以自己来实现每一步,也可以直接复用insert函数在末尾插入

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


🕯️push_front函数

它和上面push_back函数讲的一样,不过这是在开头插入


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


🕯️pop_back函数

复用erase函数
void pop_back()
{
   erase(--end());
}

🕯️pop_front函数

复用erase函数

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

🎈源码

namespace hxq
{
   template<class T>
   struct list_node
   {
      T _data;
      list_node<T>* _next;
      list_node<T>* _prev;
      list_node(const T& x = T())
         :_data(x)
         , _next(nullptr)
         , _prev(nullptr)
      {}
   };
   template<class T, class Ref, class Ptr>
   struct __list_iterator
   {
      typedef list_node<T> Node;
      typedef __list_iterator<T, Ref, Ptr> iterator;
      typedef bidirectional_iterator_tag iterator_category;
      typedef T value_type;
      typedef Ptr pointer;
      typedef Ref reference;
      typedef ptrdiff_t difference_type;
      Node* _node;
      __list_iterator(Node* node)
         :_node(node)
      {}
      bool operator!=(const iterator& it) const
      {
         return _node != it._node;
      }
      bool operator==(const iterator& it) const
      {
         return _node == it._node;
      }
      Ref operator*()
      {
         return _node->_data;
      }
      //T* operator->() 
      Ptr operator->()
      { 
         return &(operator*());
      }
      // ++it
      iterator& operator++()
      {
         _node = _node->_next;
         return *this;
      }
      // it++
      iterator operator++(int)
      {
         iterator tmp(*this);
         _node = _node->_next;
         return tmp;
      }
      // --it
      iterator& operator--()
      {
         _node = _node->_prev;
         return *this;
      }
      // it--
      iterator operator--(int)
      {
         iterator tmp(*this);
         _node = _node->_prev;
         return tmp;
      }
   };
   template<class T>
   class list
   {
      typedef list_node<T> Node;
   public:
      typedef __list_iterator<T, T&, T*> iterator;
      typedef __list_iterator<T, const T&, const T*> const_iterator;
      const_iterator begin() const
      {
         return const_iterator(_head->_next);
      }
      const_iterator end() const
      {
         return const_iterator(_head);
      }
      iterator begin()
      {
         return iterator(_head->_next);
      }
      iterator end()
      {
         return iterator(_head);
      }
      list()
      {
         _head = new Node;
         _head->_next = _head;
         _head->_prev = _head;
      }
      void push_back(const T& x)
      {
         //Node* tail = _head->_prev;
         //Node* newnode = new Node(x);
          _head          tail  newnode
         //tail->_next = newnode;
         //newnode->_prev = tail;
         //newnode->_next = _head;
         //_head->_prev = newnode;
         insert(end(), x);
      }
      void push_front(const T& x)
      {
         insert(begin(), x);
      }
      iterator insert(iterator pos, const T& x)
      {
         Node* cur = pos._node;
         Node* prev = cur->_prev;
         Node* newnode = new Node(x);
         prev->_next = newnode;
         newnode->_prev = prev;
         newnode->_next = cur;
         cur->_prev = newnode;
         return iterator(newnode);
      }
      void pop_back()
      {
         erase(--end());
      }
      void pop_front()
      {
         erase(begin());
      }
      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 iterator(next);
      }
   private:
      Node* _head;
   };
}


📍后记

本文主要介绍了STL中双向链表list的模拟实现。


✨通过结构体定义list_node节点,通过模板实现数据类型的不确定性,并对节点进行初始化。


✨利用迭代器iterator实现指针的功能,包括构造函数、解引用、*it、->、前后置++/–、!=和==等操作。


✨在list类中,通过双向链表实现了begin()/end()、const_begin()/const_end()、insert、erase、push_back、push_front、pop_back和pop_front等函数。


✨其中,push_back和push_front函数可以复用insert函数,在末尾和开头插入元素。


✨pop_back和pop_front函数可以复用erase函数,删除末尾和开头的元素。


感谢大家支持!!!


respect!


下篇见!


相关文章
|
编译器 C++ 容器
【c++丨STL】基于红黑树模拟实现set和map(附源码)
本文基于红黑树的实现,模拟了STL中的`set`和`map`容器。通过封装同一棵红黑树并进行适配修改,实现了两种容器的功能。主要步骤包括:1) 修改红黑树节点结构以支持不同数据类型;2) 使用仿函数适配键值比较逻辑;3) 实现双向迭代器支持遍历操作;4) 封装`insert`、`find`等接口,并为`map`实现`operator[]`。最终,通过测试代码验证了功能的正确性。此实现减少了代码冗余,展示了模板与仿函数的强大灵活性。
527 2
|
缓存 算法 程序员
C++STL底层原理:探秘标准模板库的内部机制
🌟蒋星熠Jaxonic带你深入STL底层:从容器内存管理到红黑树、哈希表,剖析迭代器、算法与分配器核心机制,揭秘C++标准库的高效设计哲学与性能优化实践。
1070 3
C++STL底层原理:探秘标准模板库的内部机制
|
存储 算法 C++
【c++丨STL】map/multimap的使用
本文详细介绍了STL关联式容器中的`map`和`multimap`的使用方法。`map`基于红黑树实现,内部元素按键自动升序排列,存储键值对,支持通过键访问或修改值;而`multimap`允许存在重复键。文章从构造函数、迭代器、容量接口、元素访问接口、增删操作到其他操作接口全面解析了`map`的功能,并通过实例演示了如何用`map`统计字符串数组中各元素的出现次数。最后对比了`map`与`set`的区别,强调了`map`在处理键值关系时的优势。
1029 73
|
存储 缓存 C++
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
C++ 标准模板库(STL)提供了一组功能强大的容器类,用于存储和操作数据集合。不同的容器具有独特的特性和应用场景,因此选择合适的容器对于程序的性能和代码的可读性至关重要。对于刚接触 C++ 的开发者来说,了解这些容器的基础知识以及它们的特点是迈向高效编程的重要一步。本文将详细介绍 C++ 常用的容器,包括序列容器(`std::vector`、`std::array`、`std::list`、`std::deque`)、关联容器(`std::set`、`std::map`)和无序容器(`std::unordered_set`、`std::unordered_map`),全面解析它们的特点、用法
1228 1
C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程
|
算法 C++ 容器
模拟实现c++中的list模版
模拟实现c++中的list模版
|
C++ 容器
【c++丨STL】stack和queue的使用及模拟实现
本文介绍了STL中的两个重要容器适配器:栈(stack)和队列(queue)。容器适配器是在已有容器基础上添加新特性或功能的结构,如栈基于顺序表或链表限制操作实现。文章详细讲解了stack和queue的主要成员函数(empty、size、top/front/back、push/pop、swap),并提供了使用示例和模拟实现代码。通过这些内容,读者可以更好地理解这两种数据结构的工作原理及其实现方法。最后,作者鼓励读者点赞支持。 总结:本文深入浅出地讲解了STL中stack和queue的使用方法及其模拟实现,帮助读者掌握这两种容器适配器的特性和应用场景。
581 21
|
存储 算法 C++
【c++丨STL】set/multiset的使用
本文深入解析了STL中的`set`和`multiset`容器,二者均为关联式容器,底层基于红黑树实现。`set`支持唯一性元素存储并自动排序,适用于高效查找场景;`multiset`允许重复元素。两者均具备O(logN)的插入、删除与查找复杂度。文章详细介绍了构造函数、迭代器、容量接口、增删操作(如`insert`、`erase`)、查找统计(如`find`、`count`)及`multiset`特有的区间操作(如`lower_bound`、`upper_bound`、`equal_range`)。最后预告了`map`容器的学习,其作为键值对存储的关联式容器,同样基于红黑树,具有高效操作特性。
905 3
|
存储 算法 C++
【c++丨STL】priority_queue(优先级队列)的使用与模拟实现
本文介绍了STL中的容器适配器`priority_queue`(优先级队列)。`priority_queue`根据严格的弱排序标准设计,确保其第一个元素始终是最大元素。它底层使用堆结构实现,支持大堆和小堆,默认为大堆。常用操作包括构造函数、`empty`、`size`、`top`、`push`、`pop`和`swap`等。我们还模拟实现了`priority_queue`,通过仿函数控制堆的类型,并调用封装容器的接口实现功能。最后,感谢大家的支持与关注。
1171 1
|
编译器 C语言 C++
【c++丨STL】list模拟实现(附源码)
本文介绍了如何模拟实现C++中的`list`容器。`list`底层采用双向带头循环链表结构,相较于`vector`和`string`更为复杂。文章首先回顾了`list`的基本结构和常用接口,然后详细讲解了节点、迭代器及容器的实现过程。 最终,通过这些步骤,我们成功模拟实现了`list`容器的功能。文章最后提供了完整的代码实现,并简要总结了实现过程中的关键点。 如果你对双向链表或`list`的底层实现感兴趣,建议先掌握相关基础知识后再阅读本文,以便更好地理解内容。
514 2
|
存储 算法 C++
深入浅出 C++ STL:解锁高效编程的秘密武器
C++ 标准模板库(STL)是现代 C++ 的核心部分之一,为开发者提供了丰富的预定义数据结构和算法,极大地提升了编程效率和代码的可读性。理解和掌握 STL 对于 C++ 开发者来说至关重要。以下是对 STL 的详细介绍,涵盖其基础知识、发展历史、核心组件、重要性和学习方法。