#include <iostream>
using namespace std;
template <typename T>
class MyVector
{
private:
T *first;
T *last;
T *end;
public:
MyVector() {}
//构造函数
MyVector(int size) {
first = new T[size];
last = first;
end = first + size;
}
//析构函数
~MyVector()
{
delete [] first;
first = last = end = nullptr;
}
//拷贝构造
MyVector(const MyVector &other){
//分别求出other的元素数量和容量
int size = other.last - other.first;
int capicity = other.end - other.first;
this->first = new T[capicity];
memcpy(this->first, other.first, sizeof(T) * size);
this->last = this->first + size;
this->end = this->first + capicity;
}
//拷贝赋值
MyVector &operator=(const MyVector &other)
{
if (this == &other)
{
return *this;
}
delete [] first; //先释放原来的空间
int size = other.last - other.first;
int capicity = other.end - other.first;
this->first = new T[capicity];
memcpy(this->first, other.first, sizeof(T) * size);
this->last = this->first + size;
this->end = this->first + capicity;
}
//尾插
int push_back(T data)
{
if (full())
{
greater();
}
*last = data;
last++;
return 0;
}
//尾删
int pop_back()
{
if (empty())
{
return -1;
}
last--;
return 0;
}
//判空
bool empty()
{
return this->first == this->last;
}
//判满
bool full()
{
return this->last == this->end;
}
//二倍扩容
int greater()
{
int size = last - first;
T *temp = new T[2 * size];
memcpy(temp, this->first, size * sizeof(T));
delete []first;
first = temp;
last = first + size;
end = first + 2 * size;
return 0;
}
//at
T &at(int index)
{
return first[index];
}
//清空所有元素
void clear()
{
last = first;
}
//获取当前元素的数量
int size()
{
return last - first;
}
//获取当前最大容量
int capicity()
{
return end - first;
}
//获取首个元素的引用
T &front()const
{
return *first;
}
//获取尾部元素的引用
T &back()
{
return *(last - 1);
}
};
int main()
{
MyVector<int> mv1(5);
for (int i = 0; i < 10; i++)
{
mv1.push_back(i);
}
for (int i = 0; i < 10; i++)
{
cout << mv1.at(i) << " ";
}
cout << endl;
//拷贝构造
MyVector<int> mv2(mv1);
for (int i = 0; i < 10; i++)
{
cout << mv2.at(i) << " ";
}
cout << endl;
//拷贝赋值
mv1.clear();
cout << "size:" << mv1.size() << " capicity:" << mv1.capicity() << endl;
mv1 = mv2;
cout << "size:" << mv1.size() << " capicity:" << mv1.capicity() << endl;
for (int i = 0; i < 10; i++)
{
cout << mv1.at(i) << " ";
}
cout << endl;
//尾删
mv1.pop_back();
mv1.pop_back();
for (int i = 0; i < mv1.size(); i++)
{
cout << mv1.at(i) << " ";
}
cout << endl;
//首个元素和尾部元素的引用
mv1.front() = 1;
mv1.back() = 1;
for (int i = 0; i < mv1.size(); i++)
{
cout << mv1.at(i) << " ";
}
cout << endl;
return 0;
}
自己封装vector
于 2023-07-24 21:42:08 首次发布