C++ DAY7

#include 
using namespace std;

template
class Myvector
{
private:
    T *first;
    T *last;
    T *end;

public:
    // 构造函数
    Myvector()
        : first(nullptr), last(nullptr), end(nullptr)
    {}

    // 析构函数
    ~Myvector()
    {
        delete[] first;
    }

    // 拷贝构造函数
    Myvector(const Myvector& other)
    {
        int size = other.size();
        first = new T[size];
        last = first + size;
        end = last;
        for (int i = 0; i < size; i++) {
            first[i] = other.first[i];
        }
    }

    // 拷贝赋值运算符
    Myvector& operator=(const Myvector& other)
    {
        if (this != &other) {
            delete[] first;
            int size = other.size();
            first = new T[size];
            last = first + size;
            end = last;
            for (int i = 0; i < size; i++) {
                first[i] = other.first[i];
            }
        }
        return *this;
    }

    // 获取指定位置的元素
    T& at(int index)
    {
        if (index >= 0 && index < size()) {
            return first[index];
        }
        // 处理索引越界的情况,这里简化为直接抛出异常
        throw out_of_range("Index out of range!");
    }

    // 判断向量是否为空
    bool empty()
    {
        return (first == last);
    }

    // 判断向量是否已满
    bool full()
    {
        return (last == end);
    }

    // 返回向量的首个元素
    T& front()
    {
        return *first;
    }

    // 返回向量的最后一个元素
    T& back()
    {
        return *(last - 1);
    }

    // 返回向量的大小(元素个数)
    int size()
    {
        return (last - first);
    }

    // 清空向量
    void clear()
    {
        delete[] first;
        first = nullptr;
        last = nullptr;
        end = nullptr;
    }

    // 扩容,增加二倍大小
    void expand()
    {
        int capacity = end - first;
        int newSize = capacity * 2;
        T* newFirst = new T[newSize];
        T* newLast = newFirst + size();
        T* newEnd = newFirst + newSize;

        for (int i = 0; i < size(); i++) {
            newFirst[i] = first[i];
        }

        delete[] first;
        first = newFirst;
        last = newLast;
        end = newEnd;
    }

    // 在末尾添加元素
    void push_back(const T& value)
    {
        if (full()) {
            expand();
        }
        *last = value;
        last++;
    }

    // 删除末尾的元素
    void pop_back()
    {
        if (!empty()) {
            last--;
            // 对于自定义类型的元素,可能需要执行析构函数释放资源
            // last->~T();
        }
    }
};

int main() {
    Myvector vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);

    cout << "size: " << vec.size() << endl;
    cout << "front: " << vec.front() << endl;
    cout << "back: " << vec.back() << endl;

    vec.pop_back();
    cout << "size: " << vec.size() << endl;
    cout << "front: " << vec.front() << endl;
    cout << "back: " << vec.back() << endl;

    return 0;
}

你可能感兴趣的:(c++,算法,开发语言)