C++实现顺序表的方法
作者:zgw285763054
本文给大家带来了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++实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!