#include <iostream>
using namespace std;
template<typename T>
class vvector
{
public:
typedef T _type;
typedef T* it;
private:
_type* _data;
size_t _size;
size_t _capacity;
public:
vvector() { //构造函数
_data = NULL;
_size = 0;
_capacity = 0;
}
~vvector() { //析构函数
delete [] _data;
_data = NULL;
_size = 0;
_capacity = 0;
}
vvector(const vvector& vec) { //拷贝构造函数
_size = vec._size;
_capacity = vec._capacity;
_data = new _type[_capacity];
for (int i = 0;i < _size;i++) {
_data[i] = vec._data[i];
}
}
vvector& operator=(const vvector& vec) { //重载运算符=
if(this == &vec) return *this;
for (int i = 0;i < vec._size;i++) {
_data[i] = vec._data[i];
}
_type* temp = new _type[_capacity];
delete [] _data;
_data = temp;
_size = vec._size;
_capacity = vec._capacity;
}
_type& operator[](size_t index) { //重载运算符[]
return _data[index];
}
bool operator ==(const vvector& vec) const { //重载运算符==
if (_size != vec._size) return false;
for (int i = 0;i < _size;i++) {
if(_data[i] != vec._data[i]){
return false;
}
}
return true;
}
void push_back(_type val) { //尾部添加元素
if (_capacity == 0) {
_capacity = 1;
_data = new _type[_capacity];
} else {
if(_size+1 > _capacity) {
_capacity <<= 1;
_type* temp = new _type[_capacity];
for(int i = 0;i < _size;i++) {
temp[i] = _data[i];
}
delete [] _data;
_data = temp;
}
}
_data[_size++] = val;
}
void insert(it pos, _type val) { //任意位置迭代器插入元素
int len = pos-_data;
if (_capacity == 0) {
_capacity = 1;
_data = new _type[_capacity];
_data[0] = val;
} else if (_size+1 > _capacity) {
_capacity <<= 1;
_type* temp = new _type[_capacity];
for (int i = 0;i < len;i++) {
temp[i] = _data[i];
}
temp[len] = val;
for (int i = len;i < _size;i++) {
temp[i+1] = _data[i];
}
delete [] _data;
_data = temp;
} else {
for (int i = _size;i > len;i--) {
_data[i] = _data[i-1];
}
_data[len] = val;
}
_size++;
}
void pop_back() { //尾部删除元素
_size--;
}
void erase(it pos) { //任意位置迭代器删除元素
size_t len = pos-_data;
for(int i = len;i < _size-1;i++) {
_data[i] = _data[i+1];
}
_size--;
}
_type front()const { //返回头部元素
return _data[0];
}
_type back()const { //返回尾部元素
return _data[_size-1];
}
it begin() { //返回头部元素地址
return _data;
}
it end() { //返回尾部元素地址
return _data + _size;
}
size_t capacity() const { //返回申请空间大小
return _capacity;
}
bool empty() { //判断是否为空
return _size==0;
}
};
int main(){
vvector<string> vecs;
string s;
for(int i = 1;i <= 5;i++){
cin>>s;
vecs.push_back(s);
}
auto p = vecs.end();
p--;
vecs.insert(p, "10");
vecs.pop_back();
cout<<*vecs.begin()<<endl;
cout<<*vecs.end()<<endl;
for(auto n:vecs){
cout << n <<" ";
}
cout <<endl;
cout<<vecs.capacity()<<endl;
}
C++手写vector
最新推荐文章于 2024-07-05 17:24:57 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)