• 欢迎光临~

# 利用vector实现的基于数组的线性表

``````#include<iostream>
#include<vector>
#include<sstream>

using namespace std;

class illegalParameterValue {
public:
illegalParameterValue() : message("Illegal parameter value") {}

explicit illegalParameterValue(char *theMessage) {
message = theMessage;
}

explicit illegalParameterValue(const string &theMessage) {
message = theMessage;
cout << message << endl;
}

void outputMessge() {
cout << message << endl;
}

private:
string message;
};

template<class T>
class vectorList {
public:

// 构造函数，复制构造函数和构析函数
explicit vectorList(int initialCapacity = 10);

vectorList(const vectorList<T> &);

~vectorList() { delete element; }

bool empty() const { return element->empty(); }

int size() const { return element->size(); }

T &get(int theIndex) const;

int indexOf(const T &theElement) const;

void erase(int theIndex);

void insert(int theIndex, const T &theElement);

void output(ostream &out) const;

// 增加的方法
int Capacity() const { return (int) element->capacity(); }

// 线性表的起始和结束位置的迭代器
typedef typename vector<T>::iterator iterator;

iterator begin() { return element->begin(); }

iterator end() { return element->end(); }

vector<T> *element;
protected:
void checkIndex(int theIndex) const;

};

template<class T>
vectorList<T>::vectorList(int initialCapacity) {
// 构造函数
if (initialCapacity < 1) {
ostringstream s;
s << "Initial capacity = " << initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}
element = new vector<T>;
element->reserve(initialCapacity); // vector容量从0增加到initialCapacity
}

template<class T>
vectorList<T>::vectorList(const vectorList<T> &theList) {
// 复制构造函数
element = new vector<T>(*theList.element);
}

template<class T>
void vectorList<T>::checkIndex(int theIndex) const {
if (theIndex < 0 || theIndex >= size()) {
stringstream s;
s << "index = " << theIndex << " size = " << size();
throw illegalParameterValue(s.str());
}
}

template<class T>
void vectorList<T>::erase(int theIndex) {
// 删除索引为theIndex的元素
// 如果没有这个元素，则抛出异常
checkIndex(theIndex);
element->erase(begin() + theIndex);
}

template<class T>
void vectorList<T>::insert(int theIndex, const T &theElement) {
// 在索引为theIndex处插入元素theElement
//    checkIndex(theIndex);
element->insert(element->begin() + theIndex, theElement);
}

template<class T>
std::ostream &operator<<(std::ostream &stream, const vectorList<T> &theList) {
for (auto i = theList.begin(); i != theList.end(); ++i)
stream << *i;
return stream;
}

int main() {
auto *array1 = new vectorList<int>(20);
array1->insert(0, 1);
array1->insert(1, 2);
array1->insert(2, 3);
array1->insert(3, 4);
for (int &i: *array1)
cout << i << endl;
return 0;
}
``````
``````1
2
3
4
index = 20 size = 20
terminate called after throwing an instance of 'illegalParameterValue'

``````