为什么不能对数组元素实现排序输出呢?
#include<iostream>using namespace std;
#pragma once
template<typename T>
class Arrays
{
public:
Arrays();
~Arrays();
int add(T a);
int getcount()
{
return count;
}
T &operator[](int i)//下表运算符[]重载
{
return data[i];
}
protected:
void destroy();//销毁原来的数组
void realloc(int addlenght = 10);//对数组进行扩容
public:
void show();//显示数组元素
void order();
private:
T * data;
int count;
int maxlenght;
};
Arrays.cpp
#include "Arrays.h"
template<typename T>
Arrays<T>::Arrays()
{
data = NULL;
count = maxlenght = 0;
realloc();
}
template<typename T>
Arrays<T>::~Arrays()
{
destroy();
}
template<typename T>
void Arrays<T>::destroy()
{
if (maxlenght == 0)
return;
delete[] data;
count = maxlenght = 0;
data = NULL;
}
template<typename T>
void Arrays<T>::realloc(int addlenght )
{
int newlenght = maxlenght + addlenght;
T * temp = new T[newlenght];
if (data != NULL)
{
for (int i = 0; i < count; i++)//复制原来的数据
temp[i] = data[i];
delete[] data;//释放原来的空间
}
maxlenght = newlenght;
data = temp;//指向新的空间
}
template<typename T>
int Arrays<T>::add(T a)
{
if (count == maxlenght)
realloc();//容器已满自动扩容
data[count++] = a;
return count;
}
template<typename T>
void Arrays<T>::show()
{
for (int i = 0; i < count; i++)
cout << data[i] << "\t";
}
template<typename T>
void Arrays<T>::order()
{
for (int i = 0; i < count - 1; ++i)
{
int index = i;
int j;
for (j = i + 1; j < count; ++j)
if (data[j] < data[index])
index = j;
if (index != i)
{
T temp;
temp = data[j];
data[j] = data[index];
data[index] = temp;
}
}
}