如何重新初始化struct数组?

时间:2016-05-10 23:01:22

标签: c++ c++11

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

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});
            ...
        }
        ...
    }
}

2 个答案:

答案 0 :(得分:0)

对于案件:

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, {}); } 是这样设计的,因为编写一个接受初始化列表和普通值的函数当然是可能的:

{{1}}

答案 1 :(得分:0)

您可以按如下方式使用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

的最后一个参数中构造它
相关问题