# 线性表的顺序实现-Vector

## Vector:The implementation of list

Posted by xuepro on September 7, 2018


using ElemType = int;

class Vector {

ElemType *data{ nullptr };
int  capacity{ 0 }, n{ 0 };
public:
Vector(const int cap = 5) :capacity{ cap }, data{ new ElemType[cap] }
{}

bool insert(const int i, const ElemType &e) {
if (i < 0 || i >= n) return false;
if (n == capacity && !add_capacity())
return false;
for (auto j = n; j > i; j--)
data[j] = data[j - 1];
data[i] = e;
return true;
}

bool erase(const int i) {
if (i < 0 || i >= n) return false;
for (auto j = i; j < n - 1; j++)
data[j] = data[j + 1];
n--;
return false;
}

bool push_back(const ElemType &e) {
if (n == capacity && !add_capacity())
return false;
data[n++] = e;
return true;
}

bool pop_back(const ElemType e) {
if (n == 0) return false;
n--; return true;
}

ElemType get(const int i)const {
if (i >= 0 && i < n)
return data[i];
throw "下标非法！\n";
}

ElemType get(const int i, const ElemType &e)const {
if (i >= 0 && i < n)
return data[i] = e;
}

ElemType& operator[](int i) {
if (i >= 0 && i < n) return data[i];
else throw "下标非法";
}

ElemType operator[](const int i) const {
if (i >= 0 && i < n) return data[i];
else throw "下标非法";
}

bool add_capacity() {
ElemType *temp = new ElemType[2 * capacity];
if (!temp) return false;
for (auto i = 0; i < n; i++) {
temp[i] = data[i];
}
delete[] data;
data = temp; capacity *= 2;
return true;
}

int size() const { return n; }
};

#include <iostream>

int main() {

Vector v(2);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v[1] = 11;
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << '\t';
std::cout << std::endl;
v.erase(2);
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << '\t';
std::cout << std::endl;
v.erase(2);
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << '\t';
std::cout << std::endl;
}