温馨提示×

如何用C++实现自己的容器类

c++
小樊
82
2024-08-29 18:38:08
栏目: 编程语言

在C++中,你可以通过继承标准库中的容器类(例如std::vectorstd::list等)或者从头开始创建一个新的容器类。这里我将给出一个简单的示例,展示如何从头开始创建一个基本的动态数组(类似于std::vector):

#include<iostream>
#include<algorithm> // for std::copy
#include <stdexcept> // for std::out_of_range

template<typename T>
class MyVector {
public:
    MyVector() : data(nullptr), size(0), capacity(0) {}

    ~MyVector() {
        delete[] data;
    }

    // 复制构造函数
    MyVector(const MyVector& other) {
        data = new T[other.capacity];
        std::copy(other.data, other.data + other.size, data);
        size = other.size;
        capacity = other.capacity;
    }

    // 赋值运算符
    MyVector& operator=(const MyVector& other) {
        if (this != &other) {
            delete[] data;
            data = new T[other.capacity];
            std::copy(other.data, other.data + other.size, data);
            size = other.size;
            capacity = other.capacity;
        }
        return *this;
    }

    // 获取元素
    T& operator[](size_t index) {
        if (index >= size) {
            throw std::out_of_range("Index out of range");
        }
        return data[index];
    }

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

    // 添加元素
    void push_back(const T& value) {
        if (size == capacity) {
            reserve(capacity == 0 ? 1 : capacity * 2);
        }
        data[size++] = value;
    }

    // 预分配内存
    void reserve(size_t newCapacity) {
        if (newCapacity > capacity) {
            T* newData = new T[newCapacity];
            std::copy(data, data + size, newData);
            delete[] data;
            data = newData;
            capacity = newCapacity;
        }
    }

    // 获取当前大小
    size_t getSize() const {
        return size;
    }

    // 获取当前容量
    size_t getCapacity() const {
        return capacity;
    }

private:
    T* data;
    size_t size;
    size_t capacity;
};

int main() {
    MyVector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);

    for (size_t i = 0; i < vec.getSize(); ++i) {
        std::cout<< vec[i] << " ";
    }
    std::cout<< std::endl;

    return 0;
}

这个示例展示了一个简单的动态数组类MyVector,它支持添加元素、获取元素、预分配内存等基本操作。你可以根据需要扩展这个类,添加更多的功能和优化性能。

0