当前位置:文档之家› 一维动态数组

一维动态数组

用动态内存分配方法设计一个数组类,实现排序、插入等基本功能(特别注意拷贝构造函数的写法)#pragma once
#include<iostream>
using namespace std;
class myArrayList
{
public:
myArrayList(int n=0);
myArrayList(const int *a,int n);
myArrayList(const int *a,int n,int max);
myArrayList(const myArrayList &tList);
~myArrayList(void);
void sort();
void show();
bool orderInsert(int num);
private:
int maxLen;
int Len;
int *arrPtr;
};
#include"myArrayList.h"
myArrayList::myArrayList(int n)
{
this->arrPtr=NULL;
maxLen=Len=0;
}
myArrayList::~myArrayList(void)
{
delete [] arrPtr;
}
myArrayList::myArrayList(const int a[], int n)
{
maxLen=Len=n;
this->arrPtr=new int[maxLen];
for(int i=0;i<Len;i++)
arrPtr[i]=a[i];
}
myArrayList::myArrayList(const int a[], int n,int max)
{
maxLen=max;
Len=n;
this->arrPtr=new int[maxLen];
for(int i=0;i<Len;i++)
arrPtr[i]=a[i];
}
myArrayList::myArrayList(const myArrayList &tList)
{
maxLen=tList.maxLen;
Len=tList.Len;
this->arrPtr=new int[maxLen];
for(int i=0;i<Len;i++)
this->arrPtr[i]=tList.arrPtr[i];
}
void myArrayList::sort()
{
int pos;
for(int i=0;i<Len-1;i++)
{
pos=i;
for(int j=i+1;j<Len;j++)
if(arrPtr[j]<arrPtr[pos])
pos=j;
if(pos!=i)
{
int temp;
temp=arrPtr[i];arrPtr[i]=arrPtr[pos];arrPtr[pos]=temp;
}
}
}
void myArrayList::show()
{
cout<<" the result is:";
for(int i=0;i<Len;i++)
cout<<arrPtr[i]<<'\t';
cout<<endl;
}
bool myArrayList::orderInsert(int num)
{
if(Len==maxLen)
return false;
else
{
int i;
for(i=Len-1;arrPtr[i]>num;i--)
arrPtr[i+1]=arrPtr[i];
arrPtr[i+1]=num;
Len++;
return true;
}
}
void main()
{
int a[5];
for(int i=0;i<5;i++)
cin>>a[i];
myArrayList tList1(a,5,10);
tList1.sort();
tList1.show();
myArrayList tList2(tList1);
tList2.orderInsert(8);
tList2.show();
system("pause");
}。

相关主题