利用vector實現的基於陣列的線性表
阿新 • • 發佈:2022-05-28
#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; } // ADT方法 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'