手写简易动态数组
template<class T>
class simpleVector {
private:
int capacity;
int size;
using valueType = T;
using valuePoint = T*;
valuePoint vector;
public:
explicit simpleVector(int inputCapacity=8):
capacity(inputCapacity),
size(0),
vector(new valueType[capacity])
{ }
simpleVector(const simpleVector& other) :
size(other.getSize()),
capacity(other.getCapacity()),
vector(new valueType[other.getCapacity()])
{
for (int i = 0; i < size; ++i) {
vector[i] = other[i];
}
}
simpleVector& operator=(const simpleVector& other) {
if (this == &other)return *this;
if (capacity < other.getSize()) {
expand(other);
}
else{
for (int i = 0; i < size; ++i) {
vector[i] = other[i];
}
}
size = other.getSize();
return *this;
}
~simpleVector() {
delete[]vector;
}
private:
void expand(int newCapacity) {
valuePoint newVector = new valueType[newCapacity];
for (int i = 0; i < size; ++i) {
newVector[i] = vector[i];
}
delete[]vector;
vector = newCapacity;
capacity = newCapacity;
}
void expand(const simpleVector&other){
valuePoint newVector = new valueType[other.getCapacity()];
for (int i = 0; i < size; ++i) {
newVector[i] = other[i];
}
delete[]vector;
vector=newVector;
capacity=other.getCapacity();
}
public:
bool pushBack(valueType value) {
if (size == capacity)expand(2 * capacity);
vector[size] = value;
size++;
return true;
}
bool remove(valueType value) {
if (empty())return false;
int index = find(value);
if (index != -1) {
for (int i = index + 1; i < size; ++i) {
vector[i - 1] =vector[i];
}
--size;
return true;
}
return false;
}
int find(valueType value)const {
int i = 0;
for (; i < size; ++i) {
if (vector[i] == value)return i;
}
return -1;
}
bool empty()const {
return size == 0;
}
int getCapacity()const {
return capacity;
}
int getSize()const {
return size;
}
valueType& operator[](int index) {
if (index < 0 || index >= size)throw"Accessing is out of bound";
return vector[index];
}
const valueType& operator[](int index)const {
if (index < 0 || index >= size)throw"";
return vector[index];
}
valueType& back()const {
if (empty())throw "The vector is empty!";
return vector[size - 1];
}
valueType& front()const {
if (empty())throw"The vector is empty!";
return vector[0];
}
};