
#ifndef MYVECTOR #define MYVECTOR #includetemplate 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< 欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)