Programs & Examples
Abstraction · Study material
One queue abstraction, two implementations
A linked-list queue and a fixed-size ring buffer offer exactly the same push/pop/empty interface, so the same template function drives both and prints the same result.
#include <array>
#include <iostream>
#include <list>
// The same queue abstraction, two implementations: callers cannot tell them apart
template <typename T>
class ListQueue {
std::list<T> d_;
public:
void push(const T& x) { d_.push_back(x); }
T pop() { T x = d_.front(); d_.pop_front(); return x; }
bool empty() const { return d_.empty(); }
};
template <typename T, std::size_t N>
class RingQueue {
std::array<T, N> d_{};
std::size_t head_ = 0, count_ = 0;
public:
void push(const T& x) { d_[(head_ + count_++) % N] = x; }
T pop() { T x = d_[head_]; head_ = (head_ + 1) % N; --count_; return x; }
bool empty() const { return count_ == 0; }
};
template <typename Q>
void demo(Q q) {
for (int i = 1; i <= 3; ++i) q.push(i * 10);
std::cout << q.pop() << ' ';
q.push(40);
while (!q.empty()) std::cout << q.pop() << ' ';
std::cout << '\n';
}
int main() {
demo(ListQueue<int>{});
demo(RingQueue<int, 3>{});
return 0;
}
10 20 30 40 10 20 30 40
A stack ADT that protects its own rules
The first example in the introduction shows an abstract data type: users see stack operations only, and the class refuses illegal operations.
Layered functions that read like the requirement
The report example in the introduction builds a readable high-level function from small, single-purpose functions over standard algorithms.