顺序表的元素删除插入的问题

geyao1266 2008-03-10 01:19:59
#include<iostream.h>

struct biao
{
int *p;
int length;
int chu;
};

class shunxu
{
public:
shunxu(biao& b)
{
b.length=0;
b.chu = 100;
b.p= new int[b.length];
}

void charu(biao& b,int l,int a)
{
for(int j=b.length-1;j>=l;j--)
{
b.p[j+1]=b.p[j];
}
b.p[l]=a;
b.length++;

}

void shanchu(biao& b,int i)
{
cout<<"你删除的是顺序表中的第"<<i+1<<"个数"<<b.p[i]<<endl;
for(int j = i;j<b.length;j++)
b.p[j]=b.p[j+1];
b.length--;

}

void hebing(biao& b,biao& a)
{
int i=0;
for(int j=b.length;j<(b.length+a.length);j++)
{
b.p[j]=a.p[i];
i++;
}
b.length+=a.length;
delete a.p;
}

void disp(biao& b)
{

cout<<"现在要输出的顺序表是:"<<endl;
for(int m=0;m<b.length;m++)
{
cout<<b.p[m]<<" ";
}
}
};

void main()
{
biao b1,b2;
shunxu ab(b1);
shunxu ab1(b2);
for(int i=0;i<5;i++)
{
b1.p[i]=i+5;
b1.length++;
}
for(int j= 0;j<5;j++)
{
b2.p[j] = j+2;
b2.length++;
}


ab.shanchu(b1,3);
ab.disp(b1);


ab.disp(b2);
ab.charu(b2,1,7);
ab.disp(b2);
ab.hebing(b1,b2);
ab.disp(b1);

}

总是找不到错误,提示是内存的问题。大家帮忙看一下~
...全文
161 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jianyuanPC 2008-03-10
  • 打赏
  • 举报
回复
#include<iostream>

using namespace std;

struct biao
{
int *p;
int length;
int chu;
};

class shunxu
{
public:
shunxu(biao &b,int len)
{
b.length=len;
b.chu = 100;
b.p= new int[b.length];
}

void charu(biao &b,int l,int a)
{
for(int j=b.length-1;j >= l;j--)
{
b.p[j+1]=b.p[j];
}
b.p[l]=a;
b.length++;

}

void shanchu(biao &b,int i)
{
cout <<"你删除的是顺序表中的第" <<i+1 <<"个数" <<b.p[i]<<endl;
for(int j = i;j <b.length;j++)
b.p[j]=b.p[j+1];
b.length--;

}

void hebing(biao &b,biao &a)
{
int i=0;
for(int j=b.length;j <(b.length+a.length);j++)
{
b.p[j]=a.p[i];
i++;
}
b.length+=a.length;
//delete a.p;
}

void disp(biao& b)
{

cout <<"现在要输出的顺序表是:" <<endl;
for(int m=0;m <b.length;m++)
{
cout <<b.p[m] <<" ";
}
}
};

void main()
{
biao b1,b2;
shunxu ab(b1,5);
shunxu ab1(b2,5);
for(int i=0;i <5;i++)
{
b1.p[i]=i+5;
}
for(int j= 0;j <5;j++)
{
b2.p[j] = j+2;
}

printf("开心!\n");
ab.shanchu(b1,3);
ab.disp(b1);


ab.disp(b2);
ab.charu(b2,1,7);
ab.disp(b2);
ab.hebing(b1,b2);
ab.disp(b1);
}


/*把你的构造函数改了一下shunxu(biao &b,int len)~
b.length=0;
b.chu = 100;
b.p= new int[b.length];
注意这里的length总是为为0;
void hebing(biao& b,biao& a)函数里面不能delete delete a.p;
*/
moss830704 2008-03-10
  • 打赏
  • 举报
回复
delete a.p;

放在类shunxu的析构函数里
zcl198715 2008-03-10
  • 打赏
  • 举报
回复
shunxu(biao& b)
{
b.length=0;
b.chu = 100;
b.p= new int[b.length];
}
b.p并没有分配任何空间!
修改一下就可以了
Chappell 2008-03-10
  • 打赏
  • 举报
回复
貌似逻辑思维有点乱

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧