#include <iostream>
#include <stdexcept>

template <typename T>
class MyVector {
private:
    T* data;          // Pointer to the data array
    size_t vec_size;  // Number of elements in the vector
    size_t vec_capacity;  // Capacity of the vector

    // Function to reallocate memory
    void reallocate(size_t new_capacity) {
        T* new_data = new T[new_capacity];
        for (size_t i = 0; i < vec_size; ++i) {
            new_data[i] = data[i];
        }
        delete[] data;
        data = new_data;
        vec_capacity = new_capacity;
    }

public:
    // Constructor
    MyVector() : data(nullptr), vec_size(0), vec_capacity(0) {}

    // Destructor
    ~MyVector() {
        delete[] data;
    }

    // Add an element to the end
    void push_back(const T& value) {
        if (vec_size == vec_capacity) {
            reallocate(vec_capacity == 0 ? 1 : vec_capacity * 2);
        }
        data[vec_size++] = value;
    }

    // Get the size of the vector
    size_t size() const {
        return vec_size;
    }

    // Get the capacity of the vector
    size_t capacity() const {
        return vec_capacity;
    }

    // Access element by index
    T& operator[](size_t index) {
        if (index >= vec_size) {
            throw std::out_of_range("Index out of range");
        }
        return data[index];
    }

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

    // Clear the vector
    void clear() {
        delete[] data;
        data = nullptr;
        vec_size = 0;
        vec_capacity = 0;
    }
};

int main() {
    MyVector<int> myVector;

    // Adding elements to the vector
    myVector.push_back(1);
    myVector.push_back(2);
    myVector.push_back(3);

    // Displaying size and capacity
    std::cout << "Size: " << myVector.size() << std::endl;
    std::cout << "Capacity: " << myVector.capacity() << std::endl;

    // Accessing elements
    for (size_t i = 0; i < myVector.size(); ++i) {
        std::cout << "Element " << i << ": " << myVector[i] << std::endl;
    }

    // Clearing the vector
    myVector.clear();
    std::cout << "Size after clear: " << myVector.size() << std::endl;
    std::cout << "Capacity after clear: " << myVector.capacity() << std::endl;

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: