189 lines
No EOL
2.7 KiB
C++
189 lines
No EOL
2.7 KiB
C++
#include <stdio.h>
|
|
#include <iostream>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
|
|
class Vec
|
|
{
|
|
private:
|
|
|
|
int *v;
|
|
int LEN;
|
|
int USED;
|
|
|
|
|
|
public:
|
|
|
|
Vec(int len)
|
|
{
|
|
LEN=len*2;
|
|
v=new int[LEN];
|
|
USED=9;
|
|
|
|
for(int i=0;i<10;i++)
|
|
v[i]=i+1;
|
|
|
|
for(int i=0;i<10;i++)
|
|
swap(i,rand()%10);
|
|
}
|
|
|
|
int get(int a)
|
|
{
|
|
return v[a];
|
|
}
|
|
|
|
void put(int a,int value)
|
|
{
|
|
v[a]=value;
|
|
}
|
|
|
|
void swap(int a, int b)
|
|
{
|
|
int temp = v[a];
|
|
v[a] = v[b];
|
|
v[b] = temp;
|
|
}
|
|
|
|
void expand()
|
|
{
|
|
LEN=LEN*2;
|
|
int *p=new int[LEN];
|
|
|
|
for(int i=0;i<=USED;i++)
|
|
p[i]=v[i];
|
|
|
|
delete[] v;
|
|
v=p;
|
|
}
|
|
|
|
void shrink()
|
|
{
|
|
LEN=LEN>>1;
|
|
int *p=new int[LEN];
|
|
|
|
for(int i=0;i<=USED;i++)
|
|
p[i]=v[i];
|
|
|
|
delete[] v;
|
|
v=p;
|
|
}
|
|
|
|
int insert(int locate,int value)
|
|
{
|
|
if(locate<0||locate>USED)
|
|
return 1;
|
|
|
|
USED++;
|
|
if(USED>=LEN)
|
|
expand();
|
|
|
|
for(int i=USED;i>locate;i--)
|
|
v[i]=v[i-1];
|
|
|
|
v[locate]=value;
|
|
|
|
return 0;
|
|
}
|
|
|
|
int del(int locate,int value)
|
|
{
|
|
|
|
if(locate<0||((USED-value)<0)||((locate+value-1)>USED))
|
|
return 1;
|
|
|
|
USED=USED-value;
|
|
|
|
for(int i=locate;i<=USED;i++)
|
|
v[i]=v[i+value];
|
|
|
|
if( ( (double)USED/(double)LEN )<=0.3 )
|
|
shrink();
|
|
|
|
return 0;
|
|
}
|
|
|
|
int find(int value)
|
|
{
|
|
int i = 0;
|
|
for(i;i<=USED;i++)
|
|
{
|
|
if(v[i]==value)
|
|
{
|
|
return i;
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
void printall()
|
|
{
|
|
for(int i=0;i<USED;i++)
|
|
printf("%d\n",v[i]);
|
|
}
|
|
|
|
int getlen()
|
|
{
|
|
return LEN;
|
|
}
|
|
|
|
int getused()
|
|
{
|
|
return USED;
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
srand(time(NULL));
|
|
|
|
Vec v(10);
|
|
int temp[10]={0};
|
|
int flag;
|
|
|
|
|
|
printf("初始化,输出数组\n");
|
|
v.printall();
|
|
|
|
|
|
while(1)
|
|
{
|
|
printf("选择操作:\n1.插入\n2.删除\n3.查找\n");
|
|
scanf("%d",&flag);
|
|
|
|
switch(flag)
|
|
{
|
|
case 1:
|
|
printf("输入秩与待插入数值\n");
|
|
scanf("%d %d",&temp[0],&temp[1]);
|
|
(v.insert(temp[0],temp[1]))?(printf("非法输入\n")):(printf("输出数组\n"));
|
|
v.printall();
|
|
break;
|
|
|
|
case 2:
|
|
printf("输入秩与待删除个数\n");
|
|
scanf("%d %d",&temp[0],&temp[1]);
|
|
(v.del(temp[0],temp[1]))?(printf("非法输入\n")):(printf("输出数组\n"));
|
|
v.printall();
|
|
break;
|
|
|
|
case 3:
|
|
printf("输入要查找的数值\n");
|
|
scanf("%d",&temp[0]);
|
|
temp[2]=v.find(temp[0]);
|
|
|
|
(temp[2]==-1)?(printf("无此元素\n")):(printf("秩为%d \n",temp[2]));
|
|
break;
|
|
|
|
default:
|
|
printf("返回菜单\n");
|
|
}
|
|
|
|
|
|
|
|
|
|
flag=0;
|
|
}
|
|
return 0;
|
|
} |