【发布时间】:2013-02-19 15:17:30
【问题描述】:
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] 中的数组。
如何在 C++ 中做到这一点??
【问题讨论】:
-
停止使用原始数组并开始使用
std::vector或std::array。 -
以防万一您没有认真对待先例建议。如果你想做 C++,一般使用 std::vector 和标准库容器。
-
将您的 sample-> 更改为 samp->。 sample 是标签名,不能这样使用。
-
@Koushik:有趣的事实:它可以。
sample * sample = new struct sample; sample->x = ....;。但是,是的,应该避免将变量命名为与类相同。 -
@Zeta 我不是指 sample 是否可以这样使用,我的意思是他已经声明为 sample * samp 所以在这里他应该使用 samp 而不是 sample。在此代码示例中,这里只是标签名称:-)