#pragma once
#define DEFAULT_CAPACITY 10
template<typename T>class Vector
{
private:int _capacity ; T*_elem; int _size;//容量默认为10,指向元素的指针,向量的规模
public: Vector(int c=DEFAULT_CAPACITY) { _elem = new T[_capacity = c]; _size = 0; }//构造函数
Vector(Vector<T>const&V, int lo, int hi) { copyFrom(V._elem, lo, hi); }//向量区间复制
Vector(T* const A, int lo, int hi) { copyFrom(A, lo, hi); }//数组区间复制
~Vector() { delete[] _elem; }//析构函数
Vector(int c, T const&e);//初始化
void insert(int rank, T e);//给秩为r的元素赋值
//取出秩为r的元素值
T& operator[](int rank)const { return _elem[rank]; }//重载操作符[]
void bubblesort();//排序
void copyFrom(T* constA,int lo,int hi);//拷贝
void expand();//向量扩容
void remove(int lo,int hi);//删除操作
void remove(int rank);//单元素删除
void push_back(T e);//后面插入
T find(T e);//查找返回秩最大的那个
void deduplicate();//无序向量去重
void uniqufy();//有序向量去重
int size() { return _size; }//返回大小
bool empty() { return _size == 0 ? true : false; }//返回是否为空
};
template<typename T>Vector<T>::Vector(int c, T const&e)//初始化
{
_elem = new T[_capacity=c];
_size = c;
for (int i = 0; i < c; i++)
{
_elem[i] = e;
}
}
template<typename T>void Vector<T>::copyFrom(T* const A, int lo, int hi)
{
_elem = new T[_capacity = 2 * (hi - lo)];//分配空间
_size = 0;
while (lo < hi)
_elem[_size++] = A[lo++];
}
template<typename T>void Vector<T>::bubblesort()//冒泡排序
{
int n = _size;
for (bool sorted = false; sorted = !sorted; n--)
{
for (int i = 1; i < n; i++)
{
if (_elem[i] < _elem[i - 1])
{
swap(_elem[i], _elem[i - 1]);
sorted = false;
}
}
}
}
template<typename T>void Vector<T>::expand()
{
if (_size < _capacity) //未满无需扩容
return;
T*oldelem = _elem; _elem = new T[_capacity <<= 1];//容量翻倍
for (int i = 0; i < _size; i++)
{
_elem[i] = oldelem[i];
}
delete[] oldelem;//释放空间
}
template<typename T>void Vector<T>::insert(int rank, T e)
{
expand();//有必要即扩容
for (int i = _size; i > rank; i--) //自后向前
{
_elem[i] = _elem[i - 1];//相继后移
}
_elem[rank] = e; //插入元素
_size++; //规模增加
}
template<typename T>void Vector<T>::remove(int lo,int hi)
{
if (lo == hi)return;
for (int i = hi; i < _size; i++)//自谦向后移动位置
_elem[lo++] = _elem[i];
_size += lo - hi; //跟新规模
}
template<typename T>void Vector<T>::push_back(T e)
{
expand(); //是否扩容
_elem[_size] = e; //向后插入
_size++; //更新规模
}
template<typename T>void Vector<T>::remove(int rank)
{
return remove(rank, rank + 1);
}
template<typename T>T Vector<T>::find(T e)
{
int n = _size;
while (--n > -1 && _elem[n] != e);//逆向查找
return n; //返回-1代表查找失败
}
template<typename T>void Vector<T>::uniqufy()
{
int i = 0, j = 0;
while (++j<_size) //从前向后向前堆
{
if (_elem[i] != _elem[j])
_elem[++i] = _elem[j];
}
_size = ++i; //更新规模
}
template<typename T>void Vector<T>::deduplicate()
{
this->bubblesort();
}
Vector类实现(C++)
最新推荐文章于 2022-12-03 14:46:58 发布