问题
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 answer 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.
Thank you a lot in advance.
回答1:
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
回答2:
Using cycling custom container. Online example is here: https://ideone.com/0nEBZa
#include <array>
#include <iostream>
#include <queue>
template <typename T, size_t N = 2>
class CyclicArray {
public:
typedef typename std::array<T, N>::value_type value_type;
typedef typename std::array<T, N>::reference reference;
typedef typename std::array<T, N>::const_reference const_reference;
typedef typename std::array<T, N>::size_type size_type;
~CyclicArray() {
while (size())
pop_front();
}
void push_back(const T& v) {
if (size_ + 1 > N)
throw;
new (&array_[(front_ + size_) % N]) T(v);
++size_;
}
void pop_front() {
if (size_ < 1)
throw;
front().~T();
++front_;
--size_;
if (front_ >= N)
front_ = 0;
}
const_reference front() const {
return *reinterpret_cast<const T*>(&array_[front_]);
}
reference front() {
return *reinterpret_cast<T*>(&array_[front_]);
}
size_type size() const {
return size_;
}
private:
size_type front_ = 0;
size_type size_ = 0;
std::array<char[sizeof(T)], N> array_;
};
int main() {
std::queue<int, CyclicArray<int, 2>> queue;
queue.push(1);
queue.push(2);
queue.pop();
queue.push(3);
int f = queue.front();
queue.pop();
std::cout << f << std::endl;
f = queue.front();
queue.pop();
std::cout << f << std::endl;
return 0;
}
Outputs
2
3
来源:https://stackoverflow.com/questions/56334492/c-create-fixed-size-queue