自己实现的简单Vector

自己实现的简单Vector,第1张

自己实现的简单Vector vec.h
#ifndef MYVECTOR
#define MYVECTOR
#include 
template 
class Vector
{
public:
    T *begin_ptr;
    T *end_ptr;
    T *cap;
    T *begin() const { return begin_ptr; }
    T *end() const { return end_ptr; }
    int size() const { return end_ptr - begin_ptr; }
    int capacity() const { return cap - begin_ptr; }
    void push_back(const T &);
    Vector() : begin_ptr(nullptr), end_ptr(nullptr), cap(nullptr), data(nullptr) {}
    Vector(int length);
    Vector(const Vector &);
    Vector &operator=(const Vector &);
    ~Vector() { delete[] data; }

private:
    T *data;
    void reallocate();
};
template 
void Vector::push_back(const T &val)
{
    if (capacity() == size())
    {
        reallocate();
    }
    *end_ptr = val;
    end_ptr++;
}
template 
Vector::Vector(int length)
{
    data = new T[length];
    begin_ptr = nullptr;
    end_ptr = data;
    cap = data + length;
}
template 
Vector::Vector(const Vector &obj)
{
    delete[] data;
    data = new T[obj.size()];
    auto p = obj.begin();
    end_ptr = data;
    begin_ptr = data;
    while (p != obj.end())
    {
        *end_ptr = (*p);
        p++;
        end_ptr++;
    }
    cap = end_ptr;
}
template 
Vector &Vector::operator=(const Vector &obj)
{
    if (&obj == this)
    {
        return *this;
    }
    delete[] data;
    data = new T[obj.size()];
    auto p = obj.begin();
    end_ptr = data;
    begin_ptr = data;
    while (p != obj.end())
    {
        *end_ptr = (*p);
        p++;
        end_ptr++;
    }
    cap = end_ptr;
    return *this;
}
template 
void Vector::reallocate()
{
    int newlen = size() ? 2 * size() : 1;
    int oldsize=size();
    auto newdata=new T[newlen];
    auto p=data;
    begin_ptr= end_ptr=newdata;
    cap=newdata+newlen;
    for(int i=0;i 
test.cpp 

简单测试

#include 
#include "vec.h"

int main(int argc, char **argv)
{
    Vector vec;
    for (int i = 0; i < 1000000; i++)
    {
        vec.push_back(i);
    }
    std::cout<

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4752228.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-08
下一篇2022-11-08

发表评论

登录后才能评论

评论列表(0条)

    保存