C++实现动态顺序表实现动态顺序表
本文实例为大家分享了C++实现动态顺序表的具体代码,供大家参考,具体内容如下
Vector.h
#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()
{