【问题标题】:How to reinitialize array of struct?如何重新初始化结构数组?
【发布时间】:2016-05-10 23:01:21
【问题描述】:

正如我们在 c++ 中所知道的,我们可以重新初始化一个大小为 N 且值为 0 的数组 arr

fill (arr, arr + N, 0);

但我需要使用struct S 重新初始化数组,

struct S {
    int b[2];
}

实际代码是,

#include <iostream>

using namespace std;

struct Dog
{
    int count[2];
};

int main(){
    ...
    Dog dogs[N];

    ...
    while (T--)
    {
        ...
        for (int i = 0; i < M; ++i)
        {
            fill(dogs, dogs+N, {0});
            ...
        }
        ...
    }
}

【问题讨论】:

  • 您遇到std::fill 的问题了吗?
  • 同样使用fill
  • @M.M @juanchopanza 使用类似填充,fill (arr, arr+N, {0}) 引发数组。我知道语法没有意义,我是否必须创建一个临时结构变量来初始化?
  • 我认为语法实际上可能是有效的。是的,它需要一个临时结构,但 {0} 可能会这样做。
  • @MooingDuck 它给出了一个错误/usr/include/c++/4.8/bits/stl_algobase.h:721:5: note: template argument deduction/substitution failed:

标签: c++ c++11


【解决方案1】:

案例:

struct Dog { int count[2]; };

Dog dogs[N];

你可以使用:

std::fill(dogs, dogs+N, Dog{});

fill 的第三个参数必须已经具有正确的类型,编译器不会从迭代器中推断出类型。所以你不能只使用{}{0}

考虑使用std::begin(dogs), std::end(dogs) 而不是dogs, dog+N,因为这样可以消除对N 使用错误值的可能性。


我不知道为什么fill 是这样设计的,因为当然可以编写一个接受初始化列表和正常值的函数:

#include <algorithm>

template<typename It>
void mfill(It begin, It end, typename std::remove_reference<decltype(*begin)>::type const &v)
{
   std::fill(begin, end, v);
}

struct Dog { int count[2]; };

int main()
{
   Dog dogs[5];
   mfill(dogs, dogs+5, {});
}

【讨论】:

    【解决方案2】:

    你可以使用fill_n如下:

    struct Dog
    {
        int count[2];
    };
    
    int main(){
    
      Dog dogs[4] = {};
      dogs[0].count[0] = 1;
    
      std::fill_n(dogs, 0, Dog{});
    
    }
    

    由于Dog是一个pod结构,你可以在fill_n的最后一个参数中默认构造它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多