内存占用太多,为什么?

cbuser 2004-03-17 05:32:21
哪位能不能帮我优化一下?我这个程序不知道为什么,占用了很大的内存,速度很慢
typedef struct AList
{
int no1;
int no2;
int no3;
int no4;
int no5;

} TAList;
typedef TAList* PAList;


void __fastcall TForm1::FormCreate(TObject *Sender)
{
randomize();
ResultList = new TList;
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
DWORD StartTime,EndTime,LastTime;
StartTime=GetTickCount(); //从这开始计算下面这个循环运行的时间
for(int i=0;i<100000;i++)
{
PAList AStruct;
AStruct = new TAList;
AStruct->no1=random(10);
AStruct->no2=random(10);
AStruct->no3=random(10);
AStruct->no4=random(10);
AStruct->no5=random(10);
ResultList->Add(AStruct);

}
//开始比较,此处占用了极多的内存
for(int i=0;i<Form1->ResultList->Count-1;i++)
{
PAList AStruct;
AStruct = new TAList;
AStruct = (PAList) ResultList->Items[i];
for(int j=i+1;j<Form1->ResultList->Count;j++)
{
PAList BStruct;
BStruct = new TAList;
BStruct = (PAList) ResultList->Items[j];
int iSame=0;
if(AStruct->no1==(BStruct->no1+1)) continue;
if(AStruct->no2==(BStruct->no2+1)) continue;
if(AStruct->no3==(BStruct->no3+1)) continue;
if(AStruct->no4==(BStruct->no4+1)) continue;
if(AStruct->no5==(BStruct->no5+1)) continue;

if(AStruct->no1==(BStruct->no1+2)) continue;
if(AStruct->no2==(BStruct->no2+2)) continue;
if(AStruct->no3==(BStruct->no3+2)) continue;
if(AStruct->no4==(BStruct->no4+2)) continue;
if(AStruct->no5==(BStruct->no5+2)) continue;

ResultList->Delete(j);j--;
delete BStruct;
}

}

EndTime=GetTickCount(); //循环结束,计时也结束
LastTime=EndTime-StartTime;
Application->MessageBoxA(IntToStr(LastTime).c_str(),"运算时间",MB_ICONEXCLAMATION);
}

void __fastcall TForm1::FormDestroy(TObject *Sender)
{
if(ResultList->Count>0)
for(int i=ResultList->Count-1;i<-1;i--)
{
PAList AStruct;
AStruct = new TAList;
AStruct =(PAList) ResultList->Items[i];
ResultList->Delete(i);
delete[] AStruct;

}
}
...全文
61 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
cbuser 2004-03-17
  • 打赏
  • 举报
回复
呵呵,谢谢各位,搞定了,就是shadowstar(天作棋盘星作子,谁人敢下?) 所说,没办法,要求必须这样的,不过其实也不是那么慢,两分钟左右可以算完,谢谢!
kataboy 2004-03-17
  • 打赏
  • 举报
回复
楼主的这种做法太恐怖了。我从来没有这么BT的要求!
freshman2003 2004-03-17
  • 打赏
  • 举报
回复
100000次循环内最好不要new TList动态管理内存的类,因为它本身是动态分配内存的,你搞不清他初始到底分配了多少内存。
shadowstar 2004-03-17
  • 打赏
  • 举报
回复
PAList AStruct;
/////////////去掉这一行********* AStruct = new TAList;
AStruct = (PAList) ResultList->Items[i];

PAList BStruct;
////////////还有这############## BStruct = new TAList;
BStruct = (PAList) ResultList->Items[j];

PAList AStruct;
////////////还有@@@@@@@@ AStruct = new TAList;
AStruct =(PAList) ResultList->Items[i];

耙子 2004-03-17
  • 打赏
  • 举报
回复
你这顿循环,外层就100000次,里面还不知道多少次,效率肯定地。
不知道你这是什么程序、什么目的,不过你这么写肯定不妥,重新找一个算法吧。
极速小王子 2004-03-17
  • 打赏
  • 举报
回复
哦!这个涉及到算法分析,比较复杂,你看看算法分析的书吧!

13,825

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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