#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(int num, const T &val):first(new T[num])
{
for(int i = 0; i < num; i++)
{
first[i] = val;
}
last = first+num;
end = first+num;
}
//析构函数
~Myvector()
{
delete []first;
first = nullptr;
last = nullptr;
end = nullptr;
}
//拷贝构造
Myvector(const Myvector &other)
{
this->first = new T[other.last - other.first]; //申请空间
memcpy(this->first, other.first, sizeof(T)*(other.end - other.first)); //拷贝内容
this->end = this->first + (other.end - other.first); //设置尾指针
this->last = this->first + (other.last - other.first); //设置最大存储容量地址
}
//拷贝赋值
// Myvector &operator= (const Myvector &other)
// {
// }
//at()
T &at(int pos)
{
if(pos<0 || pos>=last-first)
{
cout << "段错误" << endl;
}
return first[pos];
}
//empty()
bool empty()
{
return first == end;
}
//full()
bool full()
{
return first == last;
}
//front() 返回第一个元素
T front()
{
return *first;
}
//back() 返回最后一个元素
int back()
{
return *(last-1);
}
//size() 返回表中元素的个数
int size()
{
return last-first;
}
//clear() 清空
void clear()
{
while(first != end)
{
pop_back();
}
}
//expand() 二倍扩容
void expand()
{
int len = end-first;
T *temp = new T[len * 2];
memcpy(temp, first, sizeof(T)*len);
delete []first;
first = temp;
last = first+len;
end = first + 2*len;
}
//push_back() 末尾增加元素
void push_back(const T &val)
{
if(full())
expand();
else
*last++ = val;
}
//pop_back() 删除末尾的元素
int pop_back()
{
if(empty())
return -1;
last--;
return 0;
}
void show()
{
for(int i = 0; i < last-first; i++)
{
cout << first[i] << " ";
}
cout << endl;
}
};
int main()
{
Myvector<int> m1(5, 3);
m1.show();
Myvector<int> m2=m1;
m2.show();
m1.push_back(9);
m1.show();
m1.pop_back();
m1.show();
return 0;
}
C++ vector
于 2023-04-25 21:53:50 首次发布
文章介绍了C++中一个名为Myvector的模板类,该类模仿了标准库中的vector,包含了构造函数、析构函数、拷贝构造函数以及一些基本操作如at()、empty()、full()、front()、back()、size()、clear()、expand()、push_back()、pop_back()和show()等方法,实现了动态数组的功能,包括内存分配、元素访问和容量调整。
摘要由CSDN通过智能技术生成