概述
#include <iostream>
#include <stdlib.h>
#include <string.h>
#define max 8
#define Elemtype int
using namespace std;
typedef struct {
Elemtype *base;
int *bounds;
int dim;//数组维数
}Array;
int n,num,bound[9],i=0;
int Loc(int d,int *bound,int *pos)
{
int num=0,i;
for (i=0;i<d-1;i++) {
num+=pos[i]*bound[i];
}
return num+pos[i];
}
int sum(Array &a)
{
int sum=1;
for (int i=0;i<a.dim;i++) {
sum*=a.bounds[i];
}
return sum;
}
int InitArray(Array &a,int d,int *bound)
{
a.bounds=(int *)malloc(sizeof(int)*d);
if (a.bounds==NULL) {
cout<<"Allocation failure."<<endl;
return -1;
}
for (int i=0;i<d;i++) {
a.bounds[i]=bound[i];
}
a.dim=d;
int s=sum(a);
a.base=(Elemtype *)malloc(sizeof(Elemtype)*s);
if (a.base==NULL) {
cout<<"Allocation failure."<<endl;
free(a.bounds);
a.bounds=NULL;
a.dim=0;
return -1;
}
memset(a.base,0,sizeof(Elemtype)*s);
cout<<"Initial successfully!"<<endl;
return 0;
}
int DestroyArray(Array &a)
{
if (a.base==NULL) {
cout<<"The array is empty."<<endl;
return -1;
}
free(a.base);
a.base=NULL;
free(a.bounds);
a.bounds=NULL;
a.dim=0;
cout<<"Successfully destruction."<<endl;
return 0;
}
int value(Array &a,Elemtype e,int *bound)
{
int s=sum(a);
int p=Loc(a.dim,a.bounds,bound);
if (p>=s) {
cout<<"Position is illegal."<<endl;
return -1;
}
*(a.base+p)=e;
cout<<"Set up success."<<endl;
return 0;
}
int Print(Array &a)
{
int s=sum(a);
for (int i=0;i<s;i++) {
cout<<*(a.base+i)<<" ";
}
cout<<endl;
return 0;
}
int main()
{
cout<<"Please enter what do you want to do. Enter 0 will exit."<<endl
<<"1.Initial Array."<<endl
<<"2.Destroy Array."<<endl
<<"3.Sets the value of the array element."<<endl
<<"4.Print all elements of the array."<<endl;
Array array;
array.base=NULL;
array.bounds=NULL;
array.dim=0;
Elemtype e;
int num;
int Bound[max];
while (cin>>n&&n) {
switch (n) {
case 1:
cout<<"How many dim do you want to create?"<<endl;
cin>>num;
cout<<"Please enter the every bound of dim."<<endl;
for (int i=0;i<num;i++) {
cin>>Bound[i];
}
InitArray(array,num,Bound);
break;
case 2:
DestroyArray(array);
break;
case 3:
if (array.base==NULL) {
cout<<"Array is empty."<<endl;
}
cout<<"Where do you want to set? Please enter "<<array.dim<<" number."<<endl;
for (int i=0;i<array.dim;i++) {
cin>>Bound[i];
}
cout<<"Please enter the number you want to set."<<endl;
cin>>e;
value(array,e,Bound);
break;
case 4:
Print(array);
}
}
return 0;
}
/*
test case:
1
2
5 6
3
0 1
9
4
*/
最后
以上就是温柔枫叶为你收集整理的数组的底层实现的全部内容,希望文章能够帮你解决数组的底层实现所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复