#include <algorithm>
#include <iostream>
class myvec {
private:
int *mdata = nullptr;
int msize = 11;
int mlastidx = -1;
void () {
if (msize <= mlastidx + 1) {
reserve(msize * 2);
}
}
void init(const myvec &vec) {
if (&vec == this)
return;
myvec newvec(vec.msize);
for (int i = 0; i <= vec.mlastidx; ++i) {
newvec.insert(vec.mdata[i]);
}
swap(newvec);
}
public:
myvec() : myvec(11) {
}
myvec(int capacity) : msize(capacity) {
try {
mdata = new int[capacity];
}
catch (const std::bad_alloc &e) {
std::cerr << e.what() << std::endl;
abort();
}
}
myvec(const myvec &vec) {
init(vec);
}
~myvec() {
delete[] mdata;
std::cout<<"deconstructed"<<std::endl;
}
const myvec &operator=(const myvec &vec) {
init(vec);
return *this;
}
int size() {
return mlastidx + 1;
}
int &operator[](int index) {
if (index < 0 || index > mlastidx)
throw "invalid access";
return mdata[index];
}
void swap(myvec &other) {
std::swap(this->msize, other.msize);
std::swap(this->mdata, other.mdata);
std::swap(this->mlastidx, other.mlastidx);
}
void reserve(int capacity) {
if (capacity <= mlastidx) {
return;
}
myvec newvec(capacity);
for (int i = 0; i <= mlastidx; ++i) {
newvec.insert(mdata[i]);
}
swap(newvec);
}
bool empty() {
return mlastidx == -1;
}
void insert(int val) {
ensureSize();
mlastidx++;
mdata[mlastidx] = val;
}
void erase(int index) {
if (index < 0 || index > mlastidx) {
return;
}
for (int i = index; i < mlastidx; ++i) {
mdata[i] = mdata[i + 1];
}
mlastidx--;
}
int find(int val) {
for (int i = 0; i <= mlastidx; ++i) {
if (mdata[i] == val) {
return i;
}
}
}
int count(int val) {
int cnt = 0;
for (int i = 0; i <= mlastidx; ++i) {
if (mdata[i] == val) {
cnt++;
}
}
return cnt;
}
void clear() {
myvec newvec(msize);
swap(newvec);
}
};
近期评论