简体   繁体   中英

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?

#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 ??? with

copyOfArray[i] = personArray[i];

or use std::array as suggested by basile

More idiomatic, using a std algorithm. I also re-typed copyOfArray to 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 = .

This should work:

Define the 'copyStruct' function like that:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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