如何复制结构数组
How do I copy a struct Array?
我被困住了,我不知道如何创建我的数组的副本。如何制作包含其原始内容的结构 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);
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组