Question 10
Back to Exercise
Write a fixed-size circular buffer whose operator[] accepts any integer, including negative ones, and wraps it into range; push values and read the last three using negative indices.
Solution
#include <array>
#include <iostream>
template <typename T, std::size_t N>
class Circular {
std::array<T, N> data_{};
std::size_t next_ = 0, count_ = 0;
static std::size_t wrap(long i) { long n = static_cast<long>(N); return static_cast<std::size_t>(((i % n) + n) % n); }
public:
void push(const T& x) { data_[next_] = x; next_ = (next_ + 1) % N; if (count_ < N) ++count_; }
// index 0 = oldest kept element, -1 = newest
T& operator[](long i) { return data_[wrap(static_cast<long>(next_ - count_) + (i < 0 ? static_cast<long>(count_) + i : i))]; }
std::size_t size() const { return count_; }
};
int main() {
Circular<int, 4> temps;
for (int t : {28, 30, 31, 29, 33, 35}) temps.push(t);
std::cout << "kept " << temps.size() << ": ";
for (long i = 0; i < static_cast<long>(temps.size()); ++i) std::cout << temps[i] << ' ';
std::cout << "| last three: " << temps[-3] << ' ' << temps[-2] << ' ' << temps[-1] << '\n';
temps[-1] = 34; // fix the latest reading
std::cout << temps[3] << '\n';
return 0;
}
kept 4: 31 29 33 35 | last three: 29 33 35 34
operator[] hides the wrap-around arithmetic: users index from the oldest element, or with negative numbers from the newest, as in Python. It returns a reference, so assignments update the buffer.
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!