从C ++中的另一个数组初始化结构内部的数组
struct sample {
int x;
int y;
int arr[10];
};
int arr2[10] = {0, 1, 2, 4, 3, 2, 2, 1, 5, 5};
int a = 19;
int b = 22;
struct sample* samp = new sample;
samp->x = a;
samp->y = b;
samp->arr = ??
在上面的示例中,我需要使用元素 arr2 [10] 初始化结构 arr [10] 中的数组.
In the above example, I need to initialize array inside the structure arr[10] with the elements of arr2[10].
如何在C ++中实现?
How to do it in C++??
如何在C ++中实现?
How to do it in C++??
最简单的解决方案是使用别人所说的std::copy
. 不要在C ++中使用memcpy
,因为std::copy
对于POD一样,但也适用于非POD,并且正确地做事".如果阵列中的类型一天更改一次,则必须重新访问进行此复制的所有位置并替换memcpy
. (而且您将错过其中一个地方,并且很难找到该错误).在C ++中使用memcpy
没有任何好处,因此从一开始就使用std::copy
.
The simplest solution is to use std::copy
as was said by others. Do not use memcpy
in C++, as std::copy
does the same for PODs but also is applicable for non-PODs and just Does The Right Thing. If the type in your array changes one day, you would have to revisit all places where you do such a copy and replace the memcpy
. (And you will miss one of the places and have a hard time to find the bug). Using memcpy
in C++ has no benefits, so use std::copy
from the start.
更好的解决方案是使用C ++数据结构,在这种情况下,请使用std::array
The better solution would be to use C++ data structures, in this case, use std::array
#include <array>
struct sample {
int x;
int y;
std::array<int, 10> arr; //C++ array instead of plain C array
};
int main()
{
std::array<int, 10> arr2 = {0, 1, 2, 4, 3, 2, 2, 1, 5, 5};
int a = 19;
int b = 22;
// 1: no need to say "struct sample*" since C++98
// 2: prefer to use smart pointers..
//sample* samp = new sample;
std::unique_ptr<sample> samp(new sample());
samp->x = a;
samp->y = b;
samp->arr = arr2; //it's as easy as it should be!
// 3: ... so ypu can't forget to delete!
//delete samp;
}
我在这里使用了unique_ptr,尽管在这个小示例中,您根本不需要使用堆分配.还要引入Grijesh的初始化:
I used unique_ptr here, although in this little example you don't need to use heap allocation at all. To bring in Grijesh's initialization in as well:
int main()
{
std::array<int, 10> arr2 = {0, 1, 2, 4, 3, 2, 2, 1, 5, 5};
int a = 19;
int b = 22;
sample samp = {a, b, arr2}; //done!
}
无需分配,无需清理,无需按元素分配.
no allocation, no cleanup, no element-wise assignment needed.