2

I have a simple example where I create an std::array of some number of Foo elements:

struct Foo
{
     Foo(int bar=0) : m_bar(bar) 
     {
       // Code depending on the value of bar
     }

     int m_bar;
};

const unsigned int num = // get array size 
std::array<Foo, num> fooArr;

When I use the initialiser list in the constructor m_bar(bar) this sets all the Foo.m_bar to 0 (as this is the default constructor parameter value). If I don't do that then it is full with garbage values.

My question is how do I pass in another value different from the default one to the constructor of every element in the array without knowing the array size before hand?

I tried using a init list when creating the array, like so: std::array<Foo, 5> fooArr{3} but that only sets the first element's m_bar to 3.

4

2 回答 2

6

您应该简单地默认构造,std::array然后使用它的fill方法用固定值填充它。许多编译器可以有效地对此进行优化,因此您无需为“额外”初始化付费。

为了满足您的用例,代码如下所示:

fooArr.fill(Foo(3));
于 2015-09-17T09:42:23.943 回答
4

用 N 个元素制作一个integer_sequence,并用一个包扩展构建数组。如果您的默认构造函数执行重要工作或不存在,这将更有用。

template<std::size_t N, class T, std::size_t... Ns>
std::array<T, N> make_repeating_array(const T& value, std::index_sequence<Ns...>) {
    return {(void(Ns), value)... };
}

template<std::size_t N, class T>
std::array<T, N> make_repeating_array(const T& value) {
    return make_repeating_array<N>(value, std::make_index_sequence<N>());
}

用于

std::array<Foo, num> fooArr = make_repeating_array<num>(Foo(5));
于 2015-09-17T09:51:24.447 回答