All submissions

FixedBuffer Class Template

#include <iostream>
using namespace std;

template<typename T, size_t N>
class FixedBuffer {

	// your code here
    private:
    T data[N];
    size_t count = 0;

public:
    void push(const T& value) {
        if (count < N) {
            data[count++] = value;
        } else {
            cout << "Buffer is full. Cannot push more elements.\n";
        }
    }

    size_t size() const {
        return count;
    }

    T& operator[](size_t index) {
        if (index >= count) {
            throw out_of_range("Index out of bounds");
        }
        return data[index];
    }

    const T& operator[](size_t index) const {
        if (index >= count) {
            throw out_of_range("Index out of bounds");
        }
        return data[index];
    }


};

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;
}
Loading...

Input

3 10 20 30

Expected Output

Buffer size: 3 10 20 30