【线性表(一)】(数组)
#ifndef ARRAY_H_#include
#include
#include
#include using namespace std;
template
class Array{
public:
Array() :
capacity_(10),
ptr_(new T[capacity_], [](T *p){delete[] p;
}),
size_(0){}
Array(size_t capacity)
:capacity_(capacity),
ptr_(new T[capacity_], [](T *p){delete[] p;
}),
size_(0){}
Array(const Array &other);
~Array(){}
//获取数组存储元素大小
size_t &size(){ return size_;
}
//判断是否为空
bool empty(){ return size_ == 0;
}
//获取数组容器的承载能力大小
size_t &max_size(){ return capacity_;
} //插入元素
void insert(const int &index, const T &value);
//删除元素
T erase(const int &index);
//修改指定位置元素
void replace(const int &index, const T &value);
//获取元素
T get(const int &index){ return *(ptr_.get() + index);
}
//打印数组
void print();
public:
void expend_capacity();
//动态扩容
size_t capacity_;
size_t size_;
shared_ptr ptr_;
};
template
Array::Array(const Array &other)
{
this->size_ = other.size_;
this->capacity_ = other.capacity_;
this->ptr_ = shared_ptr(new T[capacity_], [](T *p){delete[] p;
});
copy(other.ptr_.get(), other.ptr_.get() + other.size_, ptr_.get());
}template
void Array::expend_capacity()
{
shared_ptr temp(new T[capacity_]);
if (size_ == 0){
return;
}
else{
copy(ptr_.get(), ptr_.get() + size_, temp.get());
ptr_.swap(temp);
temp.reset();
return;
}
}template
void Array::insert(const int &index, const T &value)
{
if (index<0){
cout << "index out of range,index < 0" << endl;
exit(0);
} if (size_ + 1>capacity_){
capacity_ *= 2;
expend_capacity();
} if (index >= size_){
*(ptr_.get() + size_) = value;
}
else{
copy(ptr_.get() + index, ptr_.get() + size_, ptr_.get() + index + 1);
*(ptr_.get() + index) = value;
}
++size_;
}template
T Array::erase(const int &index)
{
if (index >= size_ || index < 0){
cout << "index out of range,index < 0 or index >= size" << endl;
exit(0);
}
if (index == size_ - 1){
--size_;
return *(ptr_.get() + index);
}
else{
T temp = *(ptr_.get() + index);
copy(ptr_.get() + index + 1, ptr_.get() + size_, ptr_.get() + index);
--size_;
return temp;
}
}template
void Array::replace(const int &index, const T &value)
{
if (index >= size_ || index < 0){
cout << "index out of range,index < 0 or index >= size" << endl;
exit(0);
} *(ptr_.get() + index) = value;
}template
void Array::print()
{
for (int i = 0;
i < size_;
++i){
cout << this->get(i) << " ";
}
cout << endl;
}#endif // !ARRAY_H_
使用:
int main()
{
//数组
Array array1;
cout << array1.max_size() << endl;
array1.insert(0, 1);
array1.insert(0, 2);
array1.insert(0, 3);
array1.print();
array1.erase(1);
cout << array1.size() << endl;
cout << array1.get(0) << endl;
array1.print();
return 0;
}
参考链接:
【【线性表(一)】(数组)】数据结构与算法学习-数组
推荐阅读
- 宽容谁
- 我要做大厨
- 急于表达——往往欲速则不达
- 增长黑客的海盗法则
- 画画吗()
- 2019-02-13——今天谈梦想()
- 远去的风筝
- 三十年后的广场舞大爷
- 叙述作文
- 20190302|20190302 复盘翻盘