LearnFrenzy
Sign in Take a free test

Classes and Objects · Class Programs · Question 8

Fixed-size circular queue class in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Implement a CircularQueue class over a fixed std::array with head/tail indexes that wrap around, supporting enqueue, dequeue, size and full/empty checks.

Solution
main.cpp
#include <array>
#include <iostream>
#include <optional>

class CircularQueue {
    static constexpr std::size_t N = 4;
    std::array<int, N> buf_{};
    std::size_t head_ = 0, count_ = 0;
public:
    bool enqueue(int x) {
        if (count_ == N) return false;
        buf_[(head_ + count_) % N] = x;     // tail position wraps around
        ++count_;
        return true;
    }
    std::optional<int> dequeue() {
        if (count_ == 0) return std::nullopt;
        int x = buf_[head_];
        head_ = (head_ + 1) % N;
        --count_;
        return x;
    }
    std::size_t size() const { return count_; }
};

int main() {
    CircularQueue q;
    for (int v = 1; v <= 5; ++v) std::cout << (q.enqueue(v * 10) ? '+' : 'x');
    std::cout << ' ' << *q.dequeue() << ' ' << *q.dequeue() << ' ';
    q.enqueue(60);
    q.enqueue(70);
    while (auto v = q.dequeue()) std::cout << *v << ' ';
    std::cout << "size " << q.size() << '\n';
    return 0;
}

Output Verified by compiling and running

++++x 10 20 30 40 60 70 size 0

The fifth enqueue fails (full). After two dequeues, 60 and 70 reuse the freed slots at the start of the array – the modulo arithmetic makes the buffer circular.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links