C++ 创建固定大小的队列 [英] C++ Create fixed size queue

查看:33
本文介绍了C++ 创建固定大小的队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++中,如何创建一个简单的固定大小的队列?

In C++, how do you create a simple fixed size queue?

我已经用 Java 和 Python 做过多次,但我正在寻找一种基于 C++ 的方法.

I have done it multiple times in Java and Python but am looking for a C++ based way of doing so.

我需要一个只有 2 个元素的简单 FIFO 队列才能使用 pushpop 实用程序:我已经意识到我可以实现自己的类来执行这种限制,但我的问题是想知道是否存在任何可用的解决方案.

I need a simple FIFO queue with only 2 elements in order to use the push and pop utilities: I am already aware of the fact that I could implement my own class to perform this kind of restriction but my question aims to know if there exist any already available solution to this.

或者是否有可能用数组完成相同的任务?那也行.

Or is it maybe possible to accomplish the same task with an array? That would work as well.

推荐答案

您可以从 queue 继承,然后重新实现 push 方法.这是一个基本示例.

You could inherit from queue, and then reimplement the push method. Here is a basic example.

#include <queue>
#include <deque>
#include <iostream>

template <typename T, int MaxLen, typename Container=std::deque<T>>
class FixedQueue : public std::queue<T, Container> {
public:
    void push(const T& value) {
        if (this->size() == MaxLen) {
           this->c.pop_front();
        }
        std::queue<T, Container>::push(value);
    }
};

int main() {
    FixedQueue<int, 3> q;
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);
    q.push(5);
    q.push(6);
    q.push(7);

    while (q.size() > 0)
    {
        std::cout << q.front() << std::endl;
        q.pop();
    }
}

这将打印

$ g++ fixedqueue.cpp -std=c++17 -o fixedqueue && ./fixedqueue
5
6
7

这篇关于C++ 创建固定大小的队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆