C++完成次序表的辦法。本站提示廣大學習愛好者:(C++完成次序表的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C++完成次序表的辦法正文
空話不多說了,直接給年夜家上症結代碼了。
#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; };
以上所述是小編給年夜家引見的次序表的C++完成辦法,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!