如何复制结构数组

How do I copy a struct Array?

本文关键字:结构 数组 复制 何复制      更新时间:2023-10-16

我被困住了,我不知道如何创建我的数组的副本。如何制作包含其原始内容的结构 Person 数组的副本?

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

struct Person {
    string name;
    int age;
};
const int arraySize = 2;
Person arrayM[arraySize];
void createArray(Person personArray[], int SIZE);
void printArray(Person personArray[], int SIZE);
int main()
{
    srand(time(NULL));
    cout << "Hello world!" << endl;
    createArray(arrayM, arraySize);
    printArray(arrayM, arraySize);
    return 0;
}
void createArray(Person personArray[], int SIZE)
{
    for(int i = 0; i < arraySize; i++)
    {
        int age1 = rand() % 50 + 1;
        int age2 = rand() % 25 + 1;
        personArray[i].age = age1;
        personArray[i].age = age2;
    }
}
void printArray(Person personArray[], int SIZE)
{
    for(int i = 0; i < SIZE; i++)
    {
        cout << endl;
        cout << personArray[i].age << " " << personArray[i].age;
    }
}
void copyStruct(Person personArray[], int SIZE)
{
    int copyOfArray[SIZE];
    for(int i = 0; i < SIZE; i++)
    {
       ???
    }
}

假设int copyOfArray[SIZE]应该Person copyOfArray[SIZE]只是替换你的???

copyOfArray[i] = personArray[i];

或者按照Basile的建议使用std::array

更惯用,使用std算法。我还重新键入了 copyOfArray 以Person

void copyStruct(Person personArray[], int SIZE)
{
    Person copyOfArray[SIZE];
    std::copy(
        personArray,
        personArray + SIZE,
        +copyOfArray // + forces the array-to-pointer decay. 
    );
    // Do something with it
}

但是,如前所述,您应该宁愿使用 std::vectorstd::array ,这会重载operator =

这应该有效:

定义 'copyStruct' 函数,如下所示:

void copyStruct(Person destOfArray[], Person srcArray[], int SIZE)
{
    for(int i = 0; i < SIZE; i++) 
    {
        destOfArray[i].age = srcArray[i].age; 
        destOfArray[i].name = srcArray[i].name;
    }
}

并像这样使用函数:

Person copyOfArray[arraySize];
copyStruct(copyOfArray, arrayM, arraySize);
// Now print the content of 'copyOfArray' using your 'printArray' function
printArray(copyOfArray, arraySize);