简体   繁体   English

如何复制结构体数组?

[英]How do I copy a struct Array?

I'm stuck and I'm not sure how to go about creating a copy of my array. 我被卡住了,我不确定如何创建数组的副本。 How do I make a copy of my struct Person array with it's original content? 如何复制具有原始内容的struct 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++)
    {
       ???
    }
}

Assuming, int copyOfArray[SIZE] is supposed to be Person copyOfArray[SIZE] a just replace your ??? 假设int copyOfArray[SIZE]应该是Person copyOfArray[SIZE] ,只需替换您的???? with

copyOfArray[i] = personArray[i];

or use std::array as suggested by basile 或使用basile建议的std :: array

More idiomatic, using a std algorithm. 使用std算法更惯用。 I also re-typed copyOfArray to Person . 我也将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
}

However, as already stated, you should rather use std::vector or std::array , which overload operator = . 但是,如前所述,您应该使用std::vectorstd::array ,它们重载operator =

This should work: 这应该工作:

Define the 'copyStruct' function like that: 像这样定义'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;
    }
}

And use the function like that: 并使用如下功能:

Person copyOfArray[arraySize];
copyStruct(copyOfArray, arrayM, arraySize);

// Now print the content of 'copyOfArray' using your 'printArray' function
printArray(copyOfArray, arraySize);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM