【C++】vectorList類的實現
阿新 • • 發佈:2021-01-27
技術標籤:# 資料結構和演算法分析
**vectorList.h : **
#pragma once
#include<vector>
#include<iostream>
using namespace std;
template<class T>
class vectorList
{
protected:
void checkIndex(int theIndex) const;
vector<T>* element;//儲存線性表元素的向量
public:
vectorList(int initialCapacity = 10);
vectorList (const vectorList<T>&);
~vectorList() { delete element; }
bool empty() const { return element->empty(); }
int size() const { return (int)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()const;
};
vectorList.cpp :
#include "vectorList.h"
template<class T>
inline void vectorList<T>::checkIndex(int theIndex) const
{
if (theIndex < 0 || theIndex >= element->size() ){
cout << "index = " << theIndex << " size = " << element->size();
exit(-1);
}
}
template<class T>
vectorList<T>::vectorList(int initialCapacity)
{
if (initialCapacity < 1) {
cout<<"Initial capacity = "<<initialCapacity<<" Must be > 0";
exit(-1);
}
element = new vector<T>;
element->reserve(initialCapacity);
}
template<class T>
vectorList<T>::vectorList(const vectorList<T>& theList)
{
element = new vector<T>(*theList.element);
}
template<class T>
T& vectorList<T>::get(int theIndex) const
{
return (*element)[theIndex];
// TODO: 在此處插入 return 語句
}
template<class T>
int vectorList<T>::indexOf(const T& theElement) const
{
int theIndex = (int)(find(element->begin(), element->end(), theElement) - element->begin());
if (theIndex == size()) {
return -1;
}
return theIndex;
}
template<class T>
void vectorList<T>::erase(int theIndex)
{
checkIndex(theIndex);
element->erase(element->begin() + theIndex);
}
template<class T>
void vectorList<T>::insert(int theIndex, const T& theElement)
{
if (theIndex < 0 || theIndex > size()) {
cout << "index = " << theIndex << " size = " << size();
exit(-1);
}
element->insert(element->begin() + theIndex, theElement);
}
template<class T>
void vectorList<T>::output() const
{
for (vector<int>::iterator i = element->begin();i != element->end();i++) {
cout << *i << " ";
}
}
Test.cpp :
#include<iostream>
#include"vectorList.h"
#include"vectorList.cpp"
using namespace std;
int main() {
vectorList<int> v;
if (v.empty()) {
cout << "向量列表為空\n";
}
else
{
cout << "向量列表不為空\n";
}
v.insert(0, 9);
if (v.empty()) {
cout << "向量列表為空\n";
}
else
{
cout << "向量列表不為空\n";
}
v.insert(1, 11);
v.insert(2, 13);
v.insert(3, 15);
v.insert(4, 17);
cout << "向量列表的長度為:" << v.size()<<"\n";
cout << "獲取索引為2的元素:" << v.get(2)<<"\n";
cout << "獲取元素為17的索引:" << v.indexOf(17) << "\n";
v.output();
cout << "\n";
cout << "刪除索引為1的元素\n";
v.erase(1);
v.output();
return 0;
}