【C++】顺序表

#pragma once
#include<assert.h>
#include <iostream>
using namespace std;

typedef int DataType;

class SeqList
{
public:
	SeqList()
		:_array(NULL)
		,_size(1)
		,_capacity(1)
	{}

	SeqList(DataType* array, size_t size)
		:_array(new DataType[size])
		,_size(size)
		,_capacity(size)
	{
		memcpy(_array, array, sizeof(DataType)*size);
	}

	~SeqList()
	{
		if(_array)
		{
			delete[] _array;
		}
	}

	//拷贝构造函数现代写法
	/*SeqList(const SeqList& s)
		:_array(NULL)
	{
		SeqList tmp(s._array, s._size);
		swap(_array, tmp._array);
		_size = s._size;
		_capacity = s._capacity;
	}*/

	//拷贝构造函数传统写法
	SeqList(const SeqList& s)
		:_array(new DataType[s._size])
		,_size(s._size)
		,_capacity(s._capacity)
	{
		memcpy(_array, s._array, sizeof(DataType)*s._size);
	}

	/*SeqList& operator=(SeqList s)
	{
		if(this != &s)
		{
			swap(_array, s._array);
			_size = s._size;
			_capacity = s._capacity;
		}

		return *this;
	}*/

	SeqList& operator=(const SeqList& s)
	{
		if(this != &s)
		{
			DataType* tmp = new DataType[s._size];
			delete[] _array;
			_array = tmp;
			_size = s._size;
			_capacity = s._capacity;
		}

		return *this;
	}

public:
	void Print()
	{
		for(int i = 0; i < _size; ++i)
		{
			cout<<_array[i]<<" ";
		}
		cout<<endl;
	}

	void PushBack(const DataType& data)
	{
		_CheckCapacity();

		_array[_size++] = data;
	}

	void PopBack()
	{
		if(_size > 0)
		{
			_size--;
		}
	}

	void Insert(size_t pos, const DataType& data)
	{
		_CheckCapacity();
		if(pos < _size)
		{
			for(int i = _size; i > pos; --i)
			{
				_array[i] = _array[i - 1];
			}

			_array[pos] = data;

			_size++;
		}
	}

	int Find(const DataType& data)
	{
		for(int i = 0; i < _size; ++i)
		{
			if(data == _array[i])
			{
				return i;
			}
		}

		return -1;
	}

	void Erase(size_t pos)
	{
		if(pos < _size)
		{
			for(int i = pos; i < _size - 1; ++i)
			{
				_array[i] = _array[i + 1];
			}

			_size--;
		}
	}

	DataType& operator[](size_t index)
	{
		if(index < _size)
		{
			return _array[index];
		}
	}

	size_t Size()
	{
		return _size;
	}

	size_t Capacity()
	{
		return _capacity;
	}

	/*void Reserve(size_t size)//保留空间,增容到size
	{
		_size = size;
		_CheckCapacity();
	}*/
	
	void Clear()//清空数据,不释放空间
	{
		_size = 0;
	}

	void Swap(SeqList& s)
	{
		swap(_array, s._array);
		swap(_size, s._size);
		swap(_capacity, s._capacity);
	}

private:
	void _CheckCapacity()
	{
		if(_size >= _capacity)
		{
			_capacity = _capacity * 2;
			/*DataType* tmp = new DataType[_capacity];
			memcpy(tmp, _array, sizeof(DataType)*_size);
			delete[] _array;
			_array = tmp;*/
			_array = (DataType*)realloc(_array, _capacity*sizeof(DataType));
		}
	}
private:
	DataType* _array;
	size_t _size;
	size_t _capacity;
};

你可能感兴趣的:(C++,顺序表)