前言
面试的时候遇到了,是从来没想过会出问题的手撕。竟然在面试环节下出了不少纰漏。
要点
- 构造函数:默认构造、拷贝构造、赋值运算符重载、移动构造函数、析构函数
- push_back/pop_back
代码
#include <iostream>
using namespace std;
#define DEFAULT_CAP (200)
class MyVector
{
private:
int* arr;
int size;
int capacity;
void more_capacity() {
capacity += DEFAULT_CAP;
int *tmp = new int[capacity];
for (int i = 0; i < size; ++i) {
tmp[i] = arr[i];
}
delete[] arr;
arr = tmp;
tmp = nullptr;
return;
}
public:
MyVector() {
arr = nullptr;
size = 0;
capacity = 200;
return;
}
MyVector(int _size) {
size = _size;
capacity = (size < DEFAULT_CAP) ? DEFAULT_CAP : ((size - 1) / DEFAULT_CAP) * DEFAULT_CAP + DEFAULT_CAP;
arr = new int[capacity];
return;
}
MyVector(const MyVector& _v) {
size = _v.size;
capacity = _v.capacity;
arr = new int[capacity];
for (int i = 0; i < size; ++i) {
arr[i] = _v.arr[i];
}
return;
}
MyVector(MyVector&& _v) {
size = _v.size;
capacity = _v.capacity;
arr = _v.arr;
_v.arr = nullptr;
return;
}
MyVector& operator=(const MyVector& _v) {
if (this == &_v) {
return *this;
}
delete[] arr;
size = _v.size;
capacity = _v.capacity;
arr = new int[capacity];
for (int i = 0; i < size; ++i) {
arr[i] = _v.arr[i];
}
return *this;
}
void push_back(int val) {
if (size == capacity) {
more_capacity();
}
arr[size++] = val;
return;
}
void pop_back() {
--size;
return;
}
void show() {
cout << capacity << " " << size << " " << endl;
}
};
标签:arr,MyVector,capacity,STL,之手,int,vector,return,size
From: https://www.cnblogs.com/GaogaoBlog/p/18431066