使用模板初始化序列数组
Sequence array initialization with template
我想用从0
到N - 1
的int
序列初始化数组
#include <array>
#include <iostream>
template<unsigned N>
struct XArray
{
static constexpr int array[N] = {XArray<N - 1>::array, N - 1};
};
template<>
struct XArray<1>
{
static constexpr int array[1] = {0};
};
int main(void)
{
std::array<int, 10> const a{XArray<10>::array};
for (int const & i : a)
std::cout << i << "n";
return 0;
}
我尝试过,但它不起作用,因为我的结构中的XArray<N - 1>::array
必须是int
,而不是int *
。我该怎么做?如何"连接"这些值?
我不确定这是否符合您的要求。
#include <array>
#include <iostream>
template <size_t ...I>
constexpr auto init(std::index_sequence<I...>) {
return std::array<size_t, sizeof...(I)>{I...};
}
int main(void)
{
std::array<size_t, 10> a = init(std::make_index_sequence<10>());
for (int const & i : a)
std::cout << i << "n";
return 0;
}
您可以创建一个make_array
函数模板,该模板将返回所需的std::array
,其中包含从0
到N-1
的元素,如下所示:
C++17版本
template<std::size_t N> std::array<int, N> constexpr make_array()
{
std::array<int, N> tempArray{};
int count = 0;
for(int &elem:tempArray)
{
elem = count++;
}
return tempArray;
}
int main()
{
//-------------------------------vv------>pass the size here
constexpr auto arr = make_array<10>();
//lets confirm if all objects have the expected value
for(const auto &elem: arr)
{
std::cout << elem << std::endl; //prints 1 2 3 4 5 6 7 8 with newline in between
}
}
工作演示C++17
上述程序的输出为:
0
1
2
3
4
5
6
7
8
9
C++11版本
由于std::array::begin
不是C++11中的constexpr
,因此constexpr
已被移除。
template<std::size_t N> std::array<int, N> make_array()
{
std::array<int, N> tempArray{};
int count = 0;
for(int &elem:tempArray)
{
elem = count++;
}
return tempArray;
}
int main()
{
//---------------------vv------>pass the size here
auto arr = make_array<10>();
//lets confirm if all objects have the expected value
for(const auto &elem: arr)
{
std::cout << elem << std::endl; //prints 1 2 3 4 5 6 7 8 with newline in between
}
}
工作演示C++11
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理