我动态创建了两个结构数组(player1和player1temp)。我想使用来自player1的数据进行一些计算并将其保存到player1temp。然后我想将数据从player1temp数据复制到player1。 这是一个很好的解决方案吗?
struct team
{
int value1;
int value2;
};
int main()
{
srand(time(NULL));
team *player1=new team[5];
for(int i=0; i<5; i++)
{
player1[i].value1=rand()%20;
player1[i].value2=rand()%20;
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"\n";
}
team *player1temp=new team[5];
cout<<"\n\n";
for(int i=0; i<5; i++)
{
player1temp[i].value1=rand()%20;
player1temp[i].value2=rand()%20;
cout<<"Player1temp index: "<<i<<" "<<player1temp[i].value1<<" "<<player1temp[i].value2<<"\n";
}
delete player1;
player1=player1temp;
cout<<"\n\n";
for(int i=0; i<5; i++)
{
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"\n";
}
return 0;
}
答案 0 :(得分:0)
两个错误:
如果用于数组,delete
应为delete[]
在程序结束之前,应该删除剩余的数组。
矢量会更容易:
struct team
{
int value1;
int value2;
};
int main()
{
srand(time(NULL));
std::vector<team> player1(5);
for(int i=0; i<5; i++)
{
player1[i].value1=rand()%20;
player1[i].value2=rand()%20;
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"\n";
}
std::vector<team> player1temp = player1;
cout<<"\n\n";
for(int i=0; i<5; i++)
{
player1temp[i].value1=rand()%20;
player1temp[i].value2=rand()%20;
cout<<"Player1temp index: "<<i<<" "<<player1temp[i].value1<<" "<<player1temp[i].value2<<"\n";
}
player1 = std::move(player1temp);
//don´t use player1temp anymore now
cout<<"\n\n";
for(int i=0; i<5; i++)
{
cout<<"Player1 index: "<<i<<" "<<player1[i].value1<<" "<<player1[i].value2<<"\n";
}
return 0;
}