用常量值初始化std :: array [英] Initializing a std::array with a constant value

查看:178
本文介绍了用常量值初始化std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用恒定值初始化std::array的所有元素,就像可以使用std::vector一样.

I need to initialize all elements of a std::array with a constant value, like it can be done with std::vector.

#include <vector>
#include <array>

int main()
{
  std::vector<int> v(10, 7);    // OK
  std::array<int, 10> a(7);     // does not compile, pretty frustrating
}

有没有办法优雅地做到这一点?

Is there a way to do this elegantly?

现在我正在使用它:

std::array<int, 10> a;
for (auto & v : a)
  v = 7;

但我想避免使用显式代码进行初始化.

but I'd like to avoid using explicit code for the initialisation.

推荐答案

使用std::index_sequence,您可以这样做:

namespace detail
{
    template <typename T, std::size_t ... Is>
    constexpr std::array<T, sizeof...(Is)>
    create_array(T value, std::index_sequence<Is...>)
    {
        // cast Is to void to remove the warning: unused value
        return {{(static_cast<void>(Is), value)...}};
    }
}

template <std::size_t N, typename T>
constexpr std::array<T, N> create_array(const T& value)
{
    return detail::create_array(value, std::make_index_sequence<N>());
}

随用法

auto a = create_array<10 /*, int*/>(7); // auto is std::array<int, 10>

std::fill解决方案相反,它处理非默认的可构造类型.

Which, contrary to std::fill solution, handle non default constructible type.

这篇关于用常量值初始化std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆