c++ - 使用公共(public)数据初始化多个 C++ 数组

标签 c++ arrays c++11 initialization

我有几个 const C++ 数组,我想用不同的数据对其进行初始化,但前缀始终相同。这个例子编译:

const int array_1[] = { 1, 2, 3, 5, 5 };
const int array_2[] = { 1, 2, 3, 8, 7, 6 };
// ...

是否可以不每次都指定前缀 (1, 2, 3)?这会编译并说明它,但有使用宏的缺点:

#define prefix 1, 2, 3
const int array_1[] = { prefix, 5, 5 };
const int array_2[] = { prefix, 8, 7, 6 };

要求:

  • 没有宏。
  • 您可以使用 C++11,如果需要,也可以使用 C++14。请说明需要什么版本。
  • std::array 允许使用 C 风格的数组。

最佳答案

C++11:

#include <array>
#include <utility>

template<int... Is> struct seq {};
template<int N, int... Is> struct gen_seq : gen_seq<N-1, N-1, Is...> {};
template<int... Is> struct gen_seq<0, Is...> : seq<Is...> {};

template<class T, int N, class... Rs, int... Is>
constexpr auto append(seq<Is...>, T (&lhs)[N], Rs&&... rhs)
-> std::array<T, N+sizeof...(Rs)>
{
    return {{lhs[Is]..., std::forward<Rs>(rhs)...}};
}

template<class T, int N, class... Rs>
constexpr auto append(T (&lhs)[N], Rs&&... rhs)
-> decltype( append(gen_seq<N>{}, lhs, std::forward<Rs>(rhs)...) )
{
    return append(gen_seq<N>{}, lhs, std::forward<Rs>(rhs)...);
}

constexpr int prefix[] = {1,2,3};
constexpr auto array_1 = append(prefix, 5, 5);
constexpr auto array_2 = append(prefix, 8, 7, 6);

#include <iostream>
int main()
{
    std::cout << "array_1: ";
    for(auto const& e : array_1) std::cout << e << ", ";
    std::cout << "\n";

    std::cout << "array_2: ";
    for(auto const& e : array_2) std::cout << e << ", ";
}

关于c++ - 使用公共(public)数据初始化多个 C++ 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821067/

相关文章:

c++ - 从 C++ 访问动态创建的 QML 对象

c++ - 在不使用流的情况下设置 double (ios_base::precision)

c++ - 这两种初始化成员变量的方法有区别吗?

javascript - 如何使数组值和对象键值匹配(无论顺序如何)

java - 在Java中解析JSON数组

c++ - 异常安全和 make_unique

C++ 内存管理范例

java - 安卓 OpenCV : Edit ImageView Mat without Reassigning

javascript - 使用自定义排序函数在 JavaScript 中对多维数组进行排序

c++ - 为什么无序容器不提供定义最小负载因子的接口(interface)?