#pragma once
#include<iostream>
#include<algorithm>
#include<iterator>
using namespace std;
template<class T>
class arrayList
{
friend ostream& operator<<(ostream& out, const arrayList<T>& x);
friend istream& operator>>(istream& in, const arrayList<T>& x);
public:
arrayList(int intialCapacity = 10);
arrayList(const arrayList<T>&);
~arrayList() { delete[] element; }void changeLength(T*& a, int oldLength, int newLength);//改变数组长度
void insert(int theIndex,const T& theElement);//指定位置插入
void pushBack(const T& theElement);//尾插
void earse(int theIndex);//删除
void output() const;//输出
T& get(int theIndex);//获得指定位置的元素
bool empty();//判断是否为空
int indexOf(const T& theElement)const;获得指定元素的位置
private:
T* element;
int listSize;
int arrayLength;
};
#include"arraylist.h"
template<class T>
arrayList<T>::arrayList(int intialcapacity)
{
arrayLength = intialcapacity;
element = new T[arrayLength];
listSize = 0;
}template<class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{
arrayLength = theList.arrayLength;
listSize = theList.listSize;
element = new T[arrayLength];
copy(theList.element, theList.element + listSize, element);
}template<class T>
void arrayList<T>::changeLength(T*& a, int oldLength, int newLength) {
T *temp = new T[newLength];
int number = min(oldLength, newLength);
copy(a, a + number, temp);
a = temp;
}template<class T>
void arrayList<T>::insert(int theIndex, const T &theElement) {if (listSize == arrayLength) {
changeLength(element, arrayLength, 2 * arrayLength);
arrayLength *= 2;
}
copy_backward(element + theIndex, element + listSize, element + listSize + 1);
element[theIndex] = theElement;
listSize++;
}template<class T>
void arrayList<T>::earse(int theIndex) {copy(element + theIndex + 1, element + listSize, element + theIndex);
element[--listSize].~T();
}template<class T>
void arrayList<T>::output()const {
copy(element, element + listSize, ostream_iterator<T>(cout, " "));
cout << endl;}
template<class T>
ostream& operator<<(ostream& out, const arrayList<T>& x) {
x.output(out);
return out;
}template<class T>
istream& operator>>(istream& in, const arrayList<T>& x) {
x.output(in);
return in;
}template<class T>
void arrayList<T>::pushBack(const T& theElement) {element[listSize++] = theElement;
}template<class T>
bool arrayList<T>::empty() {
if (listSize == 0) return 1;
else return 0;
}template<class T>
T& arrayList<T>::get(int theIndex) {
return element[theIndex];
}template<class T>
int arrayList<T>::indexOf(const T& theElement) const{
int theIndex = (int)(find(element, element + listSize, theElement) - element);if (theIndex == listSize) return -1;
else return theIndex;
}
测试
int main() {
arrayList<int> test(20);
test.pushBack(1);//尾插
test.pushBack(3);
test.pushBack(4);
test.pushBack(5);
test.pushBack(6);
test.insert(1, 2);//在第二个位置插入2
test.output();
test.earse(0);
test.output();
cout<<test.get(1);//获得位置2 的元素
cout << endl;
cout<<test.indexOf(5);//获得5的位置
cout << endl;
cout<<test.empty();//判断是否为空
cout << endl;
system("pause");
return 0;}