C++STL——stack与queue

简介: C++STL——stack与queue

stack与queue

这两个就是之前数据结构学过的栈和队列,只不过多了几个接口。

stack:

queue:

这两个容器没有迭代器,这是因为怕我们更改导致顺序错误。

#include<iostream>
#include<stack>
#include<queue>
int main()
{
  stack<int> a;
  a.push(1);
  a.push(2);
  a.push(3);
  a.push(4);
  a.push(5);
  queue<int> b;
  b.push(6);
  b.push(7);
  b.push(8);
  b.push(9);
  b.push(0);
  while (!a.empty())
  {
    cout << a.top() << ' ';
    a.pop();
  }
  cout << endl;
  while (!b.empty())
  {
    cout << b.front() << ' ';
    b.pop();
  }
  return 0;
}

priority_queue

这个容器是优先级队列,看起来是队列,其实内部结构并不是队列,而是一个堆。

#include<iostream>
#include<queue>
int main()
{
  priority_queue<int> a;//大堆
  priority_queue<int, vector<int>, greater<int>> b;//小堆
  a.push(3);
  a.push(0);
  a.push(9);
  a.push(5);
  a.push(6);
  while (!a.empty())
  {
    cout << a.top() << ' ';
    a.pop();
  }
  cout << endl;
  b.push(3);
  b.push(0);
  b.push(9);
  b.push(5);
  b.push(6);
  while (!b.empty())
  {
    cout << b.top() << ' ';
    b.pop();
  }
  return 0;
}

容器适配器

什么是适配器呢?生活中我们用的充电器就是,一个充电器可以给好几种手机使用。

适配器是一种设计模式:该种模式是将一个类的接口转换成客户希望的另外一个接口。

vector与list的反向迭代器模拟实现

实现的目的主要是要求无论是list还是vector都可以用这个反向迭代器。

反向迭代器其实是迭代器位置变了而已,反向迭代器的begin与正向的end,反向迭代器的end与正向的begin指向同一个位置。

namespace baiye
{
  template<class Iterator, class Ref, class Ptr>
  struct Reverse_iterator
  {
    typedef Reverse_iterator<class Iterator, class Ref, class Ptr> self;
    Reverse_iterator(Iterator it)
      :_it(it)
    {}
    Ref operator*()//区别是否有const
    {
      Iterator tmp = _it;
      return *(--tmp);//因为begin是指向正向迭代器end的原因,所以需要--
    }
    self operator++()
    {
      _it--;
      return *this;
    }
    self operator--()
    {
      _it++;
      return *this;
    }
    bool operator!=(const Iterator it)const
    {
      return it != _it;
    }
    Ref operator->()
    {
      return &(operator*());
    }
    Iterator _it;//反向迭代器的本质
  };
}

仿函数

#include<iostream>
using namespace std;
namespace baiye
{
  template<class T>
  struct greater_than
  {
    bool operator()(const T& a, const T& b)
    {
      return a > b;
    }
  };
  template<class T>
  struct less_than
  {
    bool operator()(const T& a, const T& b)
    {
      return a < b;
    }
  };
}
int main()
{
  int a = 4;
  int b = 0;
  int c = 5;
  baiye::greater_than<int> compare;
  baiye::less_than<int> contrast;
  int sum = compare(a, b);
  cout << sum << endl;
  sum = compare(a, c);
  cout << sum << endl;
  sum = contrast(a, b);
  cout << sum << endl;
  sum = contrast(a, c);
  cout << sum << endl;
  return 0;
}

仿函数其实是一个类,在函数回调他用起来比函数地址好用,如果在某一段代码需要用到函数回调,这个函数的参数特别多,写出来之后会破坏代码看起来的美感。

deque(了解)

这是一个双端队列。他是vector与list的结合体,但是又没有vector与list在某一方面好用。

链接:https://legacy.cplusplus.com/reference/deque/deque/?kw=deque

大概的结构是这样的:

图片出自侯捷老师的《STL源码剖析》。

在开辟一个deque类的时候会有一个指针数组,里面的指针指向了模板的类型,

cur是指向数组当前访问的位置,first是指向第一个位置,last指向末尾,node不是和他们三个一个层次的,而是指向指针数组的指针。

在如果一个fairse指向的空间满了,头插就会在node指向元素的下一个位置开辟空间,在第一个位置进行插入,如果想头插就会在node指向的前一个元素进行空间开辟,然后再末尾的位置进行数据写入。

cur是用来遍历node指向的内容的,他是用来实现++,- -的。

stack与queue模拟实现

stack

namespace baiye
{
    template<class T, class Con = deque<T>>//这里也可以用list或者vector
    class stack
    {
    public:
        stack()
        {}
        void push(const T& x)
        {
            _c.push_back(x);
        }
        void pop()
        {
            _c.pop_back();
        }
        T& top()
        {
            return _c.back();
        }
        const T& top()const
        {
            return _c.back();
        }
        size_t size()const
        {
            return _c.size();
        }
        bool empty()const
        {
            return _c.empty();
        }
    private:
        Con _c;
    };
}

queue

namespace baiye
{
    template<class T, class Con = deque<T>>
    class queue
    {
    public:
        queue()
        {}
        void push(const T& x)
        {
            _c.push_back(x);
        }
        void pop()
        {
            _c.pop_front();
        }
        T& back()
        {
            return _c.back();
        }
        const T& back()const
        {
            return _c.back();
        }
        T& front()
        {
            return _c.front();
        }
        const T& front()const
        {
            return _c.front();
        }
        size_t size()const
        {
            return _c.size();
        }
        bool empty()const
        {
            return _c.empty();
        }
    private:
        Con _c;
    };
}

priority_queue模拟实现

priority_queue

#include<iostream>
#include<stack>
#include<queue>
#include<deque>
#include<list>
#include<vector>
#include<algorithm>
using namespace std;
namespace baiye
{
    template<class T>
    struct less
    {
        bool operator()(const T& a, const T& b)
        {
            return a < b;
        }
    };
    template <class T, class Container = vector<T>, class Compare = less<T> >
    class priority_queue
    {
    public:
        void adjust_up(size_t child)//向上调整
        {
            Compare com;//仿函数
            while (child > 0)
            {
                if(com(c[(child - 1) / 2], c[child]))
                {
                    swap(c[child], c[(child - 1) / 2]);
                    child = (child - 1) / 2;
                }
                else
                {
                    break;
                }
            }
        }
        void adjust_down(size_t parent)//向下调整
        {
            size_t left = parent * 2 + 1;//左孩子
            Compare com;//仿函数
            while (left < c.size())
            {
                if (left + 1 < c.size() && com(c[left], c[left + 1]))
                {
                    left++;
                }
                if (com(c[parent], c[left]))
                {
                    swap(c[left], c[parent]);
                    parent = left;
                    left = parent * 2 + 1;
                }
                else
                {
                    break;
                }
            }
        }
        priority_queue()
        {}
        template <class InputIterator>
        priority_queue(InputIterator first, InputIterator last)
            :c(first,last)
        {
            for (int i = (c.size() - 2) / 2; i >= 0; i--)//建堆
            {
                adjust_down(i);
            }
        }
        bool empty() const
        {
            return c.empty();
        }
        size_t size() const
        {
            return c.size();
        }
        const T& top() const
        {          
            return c[0];
        }
        void push(const T& x)
        {
            c.push_back(x);
            adjust_up(c.size()-1);
        }
        void pop()
        {
            swap(c[0], c[c.size() - 1]);
            c.pop_back();
            adjust_down(0);
        }
    private:
        Container c;
    };
}


相关文章
|
编译器 C++ 容器
【c++丨STL】基于红黑树模拟实现set和map(附源码)
本文基于红黑树的实现,模拟了STL中的`set`和`map`容器。通过封装同一棵红黑树并进行适配修改,实现了两种容器的功能。主要步骤包括:1) 修改红黑树节点结构以支持不同数据类型;2) 使用仿函数适配键值比较逻辑;3) 实现双向迭代器支持遍历操作;4) 封装`insert`、`find`等接口,并为`map`实现`operator[]`。最终,通过测试代码验证了功能的正确性。此实现减少了代码冗余,展示了模板与仿函数的强大灵活性。
520 2
|
缓存 算法 程序员
C++STL底层原理:探秘标准模板库的内部机制
🌟蒋星熠Jaxonic带你深入STL底层:从容器内存管理到红黑树、哈希表,剖析迭代器、算法与分配器核心机制,揭秘C++标准库的高效设计哲学与性能优化实践。
1051 3
C++STL底层原理:探秘标准模板库的内部机制
|
存储 算法 C++
【c++丨STL】map/multimap的使用
本文详细介绍了STL关联式容器中的`map`和`multimap`的使用方法。`map`基于红黑树实现,内部元素按键自动升序排列,存储键值对,支持通过键访问或修改值;而`multimap`允许存在重复键。文章从构造函数、迭代器、容量接口、元素访问接口、增删操作到其他操作接口全面解析了`map`的功能,并通过实例演示了如何用`map`统计字符串数组中各元素的出现次数。最后对比了`map`与`set`的区别,强调了`map`在处理键值关系时的优势。
1019 73
|
存储 算法 C++
【c++丨STL】set/multiset的使用
本文深入解析了STL中的`set`和`multiset`容器,二者均为关联式容器,底层基于红黑树实现。`set`支持唯一性元素存储并自动排序,适用于高效查找场景;`multiset`允许重复元素。两者均具备O(logN)的插入、删除与查找复杂度。文章详细介绍了构造函数、迭代器、容量接口、增删操作(如`insert`、`erase`)、查找统计(如`find`、`count`)及`multiset`特有的区间操作(如`lower_bound`、`upper_bound`、`equal_range`)。最后预告了`map`容器的学习,其作为键值对存储的关联式容器,同样基于红黑树,具有高效操作特性。
899 3
|
存储 算法 C++
【c++丨STL】priority_queue(优先级队列)的使用与模拟实现
本文介绍了STL中的容器适配器`priority_queue`(优先级队列)。`priority_queue`根据严格的弱排序标准设计,确保其第一个元素始终是最大元素。它底层使用堆结构实现,支持大堆和小堆,默认为大堆。常用操作包括构造函数、`empty`、`size`、`top`、`push`、`pop`和`swap`等。我们还模拟实现了`priority_queue`,通过仿函数控制堆的类型,并调用封装容器的接口实现功能。最后,感谢大家的支持与关注。
1156 1
|
编译器 C++ 开发者
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
|
编译器 C++ 容器
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
C++11为C++带来了革命性变化,引入了列表初始化、右值引用、移动语义、类的新默认成员函数和lambda表达式等特性。列表初始化统一了对象初始化方式,initializer_list简化了容器多元素初始化;右值引用和移动语义优化了资源管理,减少拷贝开销;类新增移动构造和移动赋值函数提升性能;lambda表达式提供匿名函数对象,增强代码简洁性和灵活性。这些特性共同推动了现代C++编程的发展,提升了开发效率与程序性能。
755 12
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
设计模式 安全 C++
【C++进阶】特殊类设计 && 单例模式
通过对特殊类设计和单例模式的深入探讨,我们可以更好地设计和实现复杂的C++程序。特殊类设计提高了代码的安全性和可维护性,而单例模式则确保类的唯一实例性和全局访问性。理解并掌握这些高级设计技巧,对于提升C++编程水平至关重要。
414 16
|
人工智能 机器人 编译器
c++模板初阶----函数模板与类模板
class 类模板名private://类内成员声明class Apublic:A(T val):a(val){}private:T a;return 0;运行结果:注意:类模板中的成员函数若是放在类外定义时,需要加模板参数列表。return 0;
450 0