【C++】模擬Vector的實現
來自專欄編程語言
詳細的講解請看博客:
【C++】STL -- Vector容器的用法
#include<iostream>#include<Windows.h>#include<stdlib.h>#include<string.h>using namespace std;typedef int DataType;class Vector{public: //構造函數 Vector() : start(NULL) , finish(NULL) , endofstorage(NULL) {} ~Vector(); //拷貝構造 Vector(const Vector& t) { start = new DataType[t.Size()]; finish = start + t.Size(); endofstorage = start + t.Size(); memcpy(start, t.start, (sizeof(DataType)* t.Size())); } //元素個數 size_t Size() const { return finish - start; } //賦值運算符重載 Vector& operator=(Vector t) { swap(this->start, t.start); swap(this->finish, t.finish); swap(this->endofstorage, t.endofstorage); return *this; } //容量 size_t Capacity() const { return endofstorage - start; } //擴容 void Reverse(size_t n) { if (n > Capacity()) { Expand(n); } } void Expand(size_t n) { const size_t size = Size(); const size_t capacity = Capacity(); DataType* newcapacity = new DataType[n]; for (size_t i = 0; i < size;i++) { newcapacity[i] = start[i]; } delete[] start; start = newcapacity; finish = start + size; endofstorage = start + n; } //尾插 void PushBack(DataType x) { if (finish == endofstorage) { size_t newcapacity = Capacity() > 0 ? Capacity() * 2 : 3; Expand(newcapacity); } *finish = x; finish++; } //尾刪 void PopBack() { if (finish) { finish--; } } //頭插 void PushFront(DataType x) { if (finish == endofstorage) { size_t newcapacity = Capacity() > 0 ? Capacity() * 2 : 3; Expand(newcapacity); } } //列印順序表 void PrintVector() { for (size_t i = 0; i < Size(); i++) { cout << start[i] << "-->"; } cout << endl; }private: DataType* start; DataType* finish; DataType* endofstorage;};//析構函數Vector::~Vector(){ if (finish) { delete[] start; start = finish = endofstorage = NULL; }}int main(){ Vector v1; v1.PushBack(1); v1.PushBack(2); v1.PushBack(3); v1.PushBack(4); v1.PrintVector(); cout << "size:" << v1.Size() << endl; cout << "capacity:"<<v1.Capacity() << endl; v1.PopBack(); v1.PrintVector(); system("pause"); return 0;}
推薦閱讀:
※計算機科學速成課——早期編程
※心血來潮,試試專欄。
※8.2-C++遠征之繼承篇-下-學習筆記
※書單|探索數學與編程在藝術領域的應用
※從mSATA到M.2,新生代固態硬碟介面優勢解讀