本文实例为大家分享了C++实现动态顺序表的具体代码,供大家参考,具体内容如下
Vector.h
—-想了解C++实现动态顺序表分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>
#pragma once #include <stdio.h> #include <iostream> #include <assert.h> #include <string.h> using namespace std; typedef int DataType; class Vector { public: Vector() :_first(NULL) , _finish(NULL) , _endofstorage(NULL) {} Vector(const Vector& v) { if (v.Size() > 0) { _first = new DataType[v.Size()]; //只开辟原有数据所占空间大小,节省空间 memcpy(_first, v._first, sizeof(DataType)*v.Size()); if (_first) { _finish = _first + v.Size(); _endofstorage = _first + v.Size(); } else { _first = _finish = _endofstorage = NULL; } } } Vector& operator=(Vector& v) { if (this != &v) { ////传统写法 //DataType* tmp = new DataType[v.Size()]; //memcpy(tmp, _first, sizeof(DataType)*v.Size()); //delete[] _first; //_first = tmp; //_finish = _first + v.Size(); //_endofstorage = _first + v.Size(); //现代写法 swap(_first, v._first); swap(_finish, v._finish); swap(_endofstorage, v._endofstorage); } return *this; } ~Vector() { delete[] _first; _first = _finish = _endofstorage = NULL; } void Print() { DataType* cur = _first; while (cur != _finish) { cout << *cur << " "; ++cur; } cout << endl; } size_t Size() const; size_t Capacity() const; void Expand(size_t n); void PushBack(DataType x); void Reserve(size_t n); void PopBack(); void Insert(size_t pos, DataType x); void Erase(size_t pos); size_t Find(DataType x); private: DataType* _first; DataType* _finish; DataType* _endofstorage; }; size_t Vector::Size() const { return _finish - _first; } size_t Vector::Capacity() const { return _endofstorage - _first; } void Vector::Expand(size_t n) { if (n > Capacity()) { size_t size = Size(); DataType* tmp = new DataType[n]; memcpy(tmp, _first, sizeof(DataType)*size); delete[] _first; _first = tmp; _finish = _first + size; //切记更新新的_finish和_endofstorage _endofstorage = _first + n; } } void Vector::PushBack(DataType x) { //if (_finish == _endofstorage) //{ // if (Capacity() == 0) // { // Expand(3); // } // else // { // Expand(Capacity() * 2); // } /本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/485018.html