Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Create fixed size queue

Tags:

c++

queue

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

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

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.

like image 433
Employee Avatar asked May 28 '19 03:05

Employee


People also ask

How do I create a queue of fixed size?

Use the deque class from the collections module to create a fixed size queue in Python, e.g. deq = deque(maxlen=3) . The class takes a maxlen argument that determines the maximum length of the deque. Copied!

Does queue have fixed size?

It is a queue, and the size of the queue is fixed, it means that the queue cannot hold more than specified limit of number of data. In the previous picture the size of the queue is 5 because it is holding 5 integers.

How do you declare the size of a queue?

queue::size() is an inbuilt function in C++ STL which is declared in <queue> header file. queue::size() is used to check whether the size of the associated queue container. This function returns an unsigned int value, i.e the size of the queue container, or the number of elements present in a queue container.


1 Answers

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

This will print

$ g++ fixedqueue.cpp -std=c++17 -o fixedqueue && ./fixedqueue
5
6
7
like image 190
solinent Avatar answered Oct 20 '22 01:10

solinent