#ifndef SQLIST_H
#define SQLIST_H
#include < assert.h>
#include <cstddef>
#define LIST_MAX_SIZE 100
#define LISTINCREMENT 10
template <class T>
class SqList
{
public:
SqList();
~SqList();
private:
T* m_elem; //顺序表动态空间首地址
size_t m_list_size; //顺序表当前空间大小
size_t m_number; //顺序表当前个数
public:
void PushBack(T); //在尾部添加一个元素
void PopBack(); //在尾部弹出一个元素
T& operator[](size_t); //重载下标运算符
size_t Size(); //返回元素的个数
int Find(const T); //查找某元素
};
template <class T>
SqList<T>::SqList()
{
m_elem = new T[LIST_MAX_SIZE];
assert(m_elem != 0);
m_list_size = LIST_MAX_SIZE;
m_number = 0;
}
template <class T>
SqList<T>::~SqList()
{
delete[] m_elem;
}
template <class T>
void SqList<T>::PushBack(T x)
{
T* newbase;
//判断当前空间是否满
if (m_number >= m_list_size){
newbase = new T[m_list_size + LISTINCREMENT];
assert(newbase != 0);
delete[] m_elem;
m_elem = newbase;
m_list_size += LISTINCREMENT;
}
//在表后面添加一个元素
m_elem[m_number++] = x;
}
template <class T>
void SqList<T>::PopBack()
{
if (m_number > 0){
--m_number;
}
}
template <class T>
T& SqList<T>::operator[](size_t n)
{
if (n < m_number){
return m_elem[n];
}
else{
throw runtime_error("超出范围!");
}
}
template <class T>
size_t SqList<T>::Size()
{
return m_number;
}
template <class T>
int SqList<T>::Find(const T x)
{
for (size_t i = 0; i < m_number; i++){
if (m_elem[i] == x){
return i;
}
}
return -1;
}
#endif
#define SQLIST_H
#include < assert.h>
#include <cstddef>
#define LIST_MAX_SIZE 100
#define LISTINCREMENT 10
template <class T>
class SqList
{
public:
SqList();
~SqList();
private:
T* m_elem; //顺序表动态空间首地址
size_t m_list_size; //顺序表当前空间大小
size_t m_number; //顺序表当前个数
public:
void PushBack(T); //在尾部添加一个元素
void PopBack(); //在尾部弹出一个元素
T& operator[](size_t); //重载下标运算符
size_t Size(); //返回元素的个数
int Find(const T); //查找某元素
};
template <class T>
SqList<T>::SqList()
{
m_elem = new T[LIST_MAX_SIZE];
assert(m_elem != 0);
m_list_size = LIST_MAX_SIZE;
m_number = 0;
}
template <class T>
SqList<T>::~SqList()
{
delete[] m_elem;
}
template <class T>
void SqList<T>::PushBack(T x)
{
T* newbase;
//判断当前空间是否满
if (m_number >= m_list_size){
newbase = new T[m_list_size + LISTINCREMENT];
assert(newbase != 0);
delete[] m_elem;
m_elem = newbase;
m_list_size += LISTINCREMENT;
}
//在表后面添加一个元素
m_elem[m_number++] = x;
}
template <class T>
void SqList<T>::PopBack()
{
if (m_number > 0){
--m_number;
}
}
template <class T>
T& SqList<T>::operator[](size_t n)
{
if (n < m_number){
return m_elem[n];
}
else{
throw runtime_error("超出范围!");
}
}
template <class T>
size_t SqList<T>::Size()
{
return m_number;
}
template <class T>
int SqList<T>::Find(const T x)
{
for (size_t i = 0; i < m_number; i++){
if (m_elem[i] == x){
return i;
}
}
return -1;
}
#endif