数组数据处理对象实训
【实验题目和要求】
设计一个最多可以存放100个整数的类,要求这些整数按照从小到大的顺序存放在类中的数组里,可以删除数组中的数据,也可以向数组中插入数据,但是要保持从小到大的顺序,可以求出数据的多少,可以判断数组的空和满,可以显示数组中的整数。当然刚生成对象时,对象中的数组没有数据,只有一个一个地向对象中插入数据。
设计主程序先生成一个对象,然后插入100个随机数,最后显示结果。考察若生成101或110个数,结果会怎样?
再设计主程序先生成一个对象,然后插入数据{34,48,25,45,74,26,68,37,48,95,21,35,19,73,58},接着删除{48,37,35},再插入{46,18},最后显示对象中的所有数据。
设计一个最多可以存放100个整数的类,要求这些整数按照从小到大的顺序存放在类中的数组里,可以删除数组中的数据,也可以向数组中插入数据,但是要保持从小到大的顺序,可以求出数据的多少,可以判断数组的空和满,可以显示数组中的整数。当然刚生成对象时,对象中的数组没有数据,只有一个一个地向对象中插入数据。
设计主程序先生成一个对象,然后插入100个随机数,最后显示结果。考察若生成101或110个数,结果会怎样?
再设计主程序先生成一个对象,然后插入数据{34,48,25,45,74,26,68,37,48,95,21,35,19,73,58},接着删除{48,37,35},再插入{46,18},最后显示对象中的所有数据。
实训要求:
1分析数组的数据属性要求;
2.分析数组类的属性要求;
3.编制数组累的接口定义;
4生成数组类对象;
5.编制程序实现数组对象的插入和删除操作;
通过一个数组Array类的定义,其中需要两个数据成员,一个是arr【MAX】数组用于存放,一个是acount用于计数。成员函数中主要是Add()添加,Delete()删除,Display()输出,三个功能成员函数,外部定义一个可以指定范围的随机数;
代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<string.h>
#define MAX 101
using namespace std;
class Array{
private:
int arr[MAX];
int acount;
public:
Array(){acount=0;}
Array(int &,float b=0) {memset(arr,0,101);acount=b;};
int Get(int );
int Delete(int );
int Empty( int ) {
if(acount==0) return 1; else return 0;
}
int Full( int ) {
if(acount==MAX) return 1; else return 0;
}
int Display(int i) {cout <<arr[i]<<" ";}
void Display();
~Array(){cout << "执行析构函数"<<endl;};
};
int Array::Get(int m)
{
if(acount==MAX ) return 0;
int i=0;
while(i<acount){
if(m<arr[i]) break;
else i++;
}
int j=acount;
while(j>i){
arr[j]=arr[j-1];
j--;
}
acount++;
arr[i]=m;
return 1;
}
int Array::Delete(int m){
if(acount==0) return 0;
int i = 0;
while(i<acount){
if(arr[i]==m) break;
else i++;
}
if(i>=acount) {cout << "集合内无这个数删除失败"<<endl; return 0;}
for(int j=i;j<acount-1 ;j++ )
arr[j]=arr[j+1];
acount --;
cout << "删除成功";
return 1;
}
void Array::Display(){
// if(Empty()) {cout << "集合中没有数据" <<endl; return 0;}
for(int i=0; i<acount;i++ ){
cout << '\t'<< arr[i];
if(i%8==0) cout <<endl;
}
cout << endl;
}
int _integer(int start , int end){
int bace=rand();
if(bace==RAND_MAX)
return _integer(start , end);
int range=end-start; //范围
int shuiji=RAND_MAX%range;
int chushu=RAND_MAX/range;
if(bace<RAND_MAX-shuiji)
return start+bace/chushu;
else return _integer(start,end);
}
int main()
{
Array a1;
srand((unsigned)time(NULL));
for(int i=0; i< 1000;i++) //注意这里因为Array类中的数组最大只有101,后面继续添加数增加不进去
a1.Get(rand());
// a1.Get(_integer(10,100)); //实现指定整数范围内的随机数。
a1.Display();
}
/*
int main()
{
Array a2;
cout << "输入数据个数" <<endl;
int x,T;
cin >>T;
while(T--){
cin >> x;
a2.Get(x);
}
cout << endl;
cout << "输入删除几个数据:" <<endl;
int x1,T1;
cin >>T1;
while(T1--){
cin >> x1;
a2.Delete(x1);
}
a2.Get(46);
a2.Get(18);
a2.Display();
return 0;
} */