FixedBuffer Class Template

#include <iostream>
using namespace std;

template<typename T, size_t N>
class FixedBuffer {
private:
    T data[N];           
    size_t currentSize = 0;  

public:
    void push(T v)
    {
        if (currentSize < N) {
            data[currentSize++] = v;
        }
      
    }

    size_t size() const {
        return currentSize;
    }

 T operator[](size_t i) const {
        if (i >= currentSize) {
            throw out_of_range("Index out of range");
        }
        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;
}
Upvote
Downvote
Loading...

Input

3 10 20 30

Expected Output

Buffer size: 3 10 20 30