删除结构数组,更改结构地址

Deleting array of structures, changing structure adress

本文关键字:结构 地址 数组 删除      更新时间:2023-10-16

我动态创建了两个结构数组(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<<"nn";
    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<<"nn";
    for(int i=0; i<5; i++)
    {
        cout<<"Player1 index: "<<i<<"     "<<player1[i].value1<<"     "<<player1[i].value2<<"n";
    }
    return 0;
}

两个错误:
如果用于数组,delete应该是delete[]
在程序结束之前,也应该删除剩余的数组。

vector更简单:

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<<"nn";
    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<<"nn";
    for(int i=0; i<5; i++)
    {
        cout<<"Player1 index: "<<i<<"     "<<player1[i].value1<<"     "<<player1[i].value2<<"n";
    }
    return 0;
}