#include <iostream>
using namespace std;
template <typename T>
class Myvector
{
private:
T * first;
T * last;
T * end;
public:
//构造函数
Myvector(){
first = nullptr;
last = nullptr;
end = nullptr;
}
//析构函数
~Myvector(){
delete [] first;
}
//拷贝构造
Myvector(const Myvector& other){
int size = other.size();
first = new T[size];
last = first + size;
end = last;
for(int i = 0; i < size; i++){
first[i] = other.first[i];
}
}
//拷贝赋值
Myvector &operator=(const Myvector &other){
if(this != &other){
delete [] first;
int size = other.size();
first = new T[size];
last = first + size;
end = last;
for(int i = 0; i < size; i++){
first[i] = other.first[i];
}
}
}
//T &at(int index)
T &at(int index){
return first[index];
}
//empty()
bool my_empty(){
return first == last;
}
//full()
bool my_full(){
return last == end;
}
//front()
T &my_front(){
return *first;
}
//back()
T &my_back(){
return *last;
}
//size()
int my_size(){
return last - first;
}
//clear()
void my_clear(){
last = first;
}
//expand()二倍扩容函数
void expand(){
int size = this->my_size();
T *newfirst = new T[size*2];
memcpy(newfirst, first,sizeof(T)*(end-first));
delete [] first;
first = newfirst;
newfirst = NULL;
last = first + size;
end = first + 2*size;
}
//push_back()
void push_back(const T &data){
*last = data;
last++;
}
//pop_back()
void pop_back(){
if(my_empty()){
cout << "已空,删除失败!" << endl;
return;
}
last--;
}
};
int main()
{
//定义一个Myvector对象s
Myvector <int> s;
s.expand();
//循环插入元素
for(int i = 0; i < 20; i++){
s.push_back(i);
}
//输出容器大小
cout << "szie" << s.my_size() << endl;
//判满
if(s.my_full()){
cout << "满!" << endl;
}else{
cout << "未满!" << endl;
}
//判空
if(s.my_empty()){
cout << "空!" << endl;
}else{
cout << "未空!" << endl;
}
//指定位置元素查询
cout << s.at(1) << endl;
//获取第一个和最后一个元素
cout << "first = " << s.my_front() << " back = " << s.my_back() << endl;
s.my_clear();
return 0;
}
思维导图: