[英]How do I copy a struct Array?
我被卡住了,我不確定如何創建數組的副本。 如何復制具有原始內容的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++)
{
???
}
}
假設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::vector
或std::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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.