您好,登錄后才能下訂單哦!
#pragma once #include <assert.h> template<class T> class SeqList { public: SeqList() :_a(NULL) ,_size(1) ,_capacity(1) {} SeqList(T* a, size_t size) :_a(new T[size]) ,_size(size) ,_capacity(size) { for (size_t i = 0; i < _size; ++i) { _a[i] = a[i]; } } //拷貝構造函數常規寫法 /*SeqList(const SeqList<T>& s) :_a(new T[s._size]) ,_size(s._size) ,_capacity(s._capacity) { for (size_t i = 0; i < _size; ++i) _a[i] = s._a[i]; }*/ //拷貝構造函數現代寫法 SeqList(const SeqList<T>& s) :_a(NULL) { SeqList<T> tmp(s._a, s._size); swap(_a, tmp._a); _size = s._size; _capacity = s._capacity; } ~SeqList() { if (_a) delete[] _a; } //賦值運算符重載常規寫法 SeqList<T>& operator=(const SeqList<T>& s) { if (this != &s) { T* tmp = new T[s._size]; for (size_t i = 0; i < s._size; ++i) { tmp[i] = s._a[i]; } delete[] _a; _a = tmp; _size = s._size; _capacity = s._capacity; } return *this; } //賦值運算符重載現代寫法 /*SeqList<T>& operator=(SeqList<T> s) { if (this != &s) { swap(_a, s._a); _size = s._size; _capacity = s._capacity; } return *this; }*/ public: void Print() { for (size_t i = 0; i < _size; ++i) { cout<<_a[i]<<" "; } cout<<endl; } void PushBack(const T& x) { _CheckCapacity(); _a[_size++] = x; } void PopBack() { assert(_size > 0); --_size; } void Insert(int pos, const T& x) { assert(pos >= 0 && pos <= _size); _CheckCapacity(); int iIndex = _size; while (iIndex > pos) //int和size_t比較為什么不行? { _a[iIndex] = _a[iIndex-1]; --iIndex; } _a[iIndex] = x; ++_size; } void Erase(size_t pos) { assert(_size > 0 && pos < _size); size_t index = pos; while (index < _size-1) { _a[index] = _a[index+1]; ++index; } --_size; } int Find(const T& x) { for (size_t i = 0; i < _size; ++i) { if (_a[i] == x) { return i; } } return -1; } T& operator[](size_t index) { assert(index >= 0 && index < _size); return _a[index]; } void Reserve(size_t size) //保留空間,增容到size { _capacity = size; _a = (T*)realloc(_a, _capacity * sizeof(T)); } void Clear() //不釋放空間 { _size = 0; } void Size() { return _size; } protected: void _CheckCapacity() { if (_size+1 > _capacity) { _capacity = _capacity*2; _a = (T*)realloc(_a, _capacity * sizeof(T)); } } protected: T* _a; size_t _size; size_t _capacity; };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。