55. FixedBuffer Class Template

#include <iostream>
using namespace std;

template<typename T, size_t N>
class FixedBuffer {
private:
    T data[N];
    size_t count = 0;
public:
    void push(T v) {
        if (count < N) {
            data[count++] = v;
        }
    }
    size_t size() const {
        return count;
    }
    T operator[](size_t i) const {
        return data[i];
    }
};

int main() {
    int n;
    cin >> n;
    FixedBuffer<int, 10> buf;  // max 10 elements

    for (int i = 0; i < n; i++) {
        int v;
        cin >> v;
        buf.push(v);
    }

    cout << "Buffer size: " << buf.size() << "\n";
    for (size_t i = 0; i < buf.size(); i++) {
        cout << buf[i] << " ";
    }
    cout << "\n";

    return 0;
}

 

Solution Details

  • template<typename T, size_t N> makes the buffer generic:
    • T = element type (int, float, etc.).
    • N = maximum size, known at compile time.
  • push adds elements until the buffer is full.
     
  • size() reports how many elements are stored.
     
  • operator[] provides array-like access.
     

👉 In simple words:
 This is like a small box with space for N things. You can add items one by one, check how many are inside, and look at them by index.


Significance for Embedded Developers

  • Embedded systems often avoid dynamic memory (new/malloc).
  • Fixed buffers provide predictable memory usage.
  • Examples: UART receive buffer, command history, sensor sample window.
     
Loading...

Input

3 10 20 30

Expected Output

Buffer size: 3 10 20 30