【问题标题】:Initializing an array inside a structure from another array in C++ [closed]从C ++中的另一个数组初始化结构内的数组[关闭]
【发布时间】: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::vectorstd::array
  • 以防万一您没有认真对待先例建议。如果你想做 C++,一般使用 std::vector 和标准库容器。
  • 将您的 sample-> 更改为 samp->sample 是标签名,不能这样使用。
  • @Koushik:有趣的事实:它可以。 sample * sample = new struct sample; sample->x = ....;。但是,是的,应该避免将变量命名为与类相同。
  • @Zeta 我不是指 sample 是否可以这样使用,我的意思是他已经声明为 sample * samp 所以在这里他应该使用 samp 而不是 sample。在此代码示例中,这里只是标签名称:-)

标签: c++ arrays struct


【解决方案1】:

如何在 C++ 中做到这一点??

最简单的解决方案是像其他人所说的那样使用std::copy不要在 C++ 中使用 memcpy,因为 std::copy 对 POD 的作用相同,但也适用于非 POD,只是做正确的事。如果某一天数组中的类型发生变化,您将不得不重新访问所有进行此类复制的地方并替换memcpy。 (并且您错过其中一个地方并且很难找到错误)。在 C++ 中使用memcpy 没有任何好处,所以从一开始就使用std::copy

更好的解决方案是使用 C++ 数据结构,在这种情况下,使用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 的初始化:

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!
}

无需分配、无需清理、无需按元素分配。

【讨论】:

  • 好的,这是你的std::array 好:)
【解决方案2】:

你可以使用 memcpy:

memcpy(sample->arr,arr2,sizeof(int) * 10)

但我建议两者都使用 std::vector。

【讨论】:

  • 你需要:10 * sizeof(int)
  • @hannes 是的,你完全正确。
  • 首选std::copy 而不是memcpy,因此如果类型更改为非POD MyIntType,您不必返回。而且向量是动态分配,如果您知道大小并且它不会改变,则不需要它 - std::array 是这些情况下更好的容器。
【解决方案3】:

使用for循环复制数组,

for(int i=0; i<10; i++) {
    samp->arr[i]=arr2[i];
}

【讨论】:

  • 如果算法可以做到,为什么还要使用手写循环?
【解决方案4】:

通常人们会为此使用std::copy (&lt;algorithm&gt;):

std::copy(std::begin(arr2), std::end(arr2), std::begin(samp->arr));

请注意,std::begin()std::end() (&lt;iterator&gt;) 需要 C++11 支持。如果你的编译器不支持 C++11,你可以很容易地自己提供这个函数或者使用指针算法:

std::copy(arr2, arr2 + 10, samp->arr);

很遗憾,您应该尝试将std::vector 用于动态数组或将std::array (c++11) 用于固定大小的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 2011-05-09
    相关资源
    最近更新 更多