【C++】vectorList类的实现

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值