**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;
}