c++ - 使用从 1 到 N 模板参数的数字初始化 std 数组
问题描述
我有一个模板类,并想用参数中指定的std::array
数字初始化它。这该怎么做?1
N
#include <iostream>
#include <array>
template<unsigned int N>
class Jollo
{
private:
std::array<int,N> deck;
public:
Jollo()
{
static_assert(N>1,"Jollo: deck size must be higher than '1'");
deck = std::array<int,N>{1...N}; //how to do this? = {1,2,4,5,6,7,8,9,10,11,12,13,14,15}
}
};
int main()
{
Jollo<15> j;
return 0;
}
解决方案
std::iota
是你要找的:
Jollo()
{
static_assert(N>1,"Jollo: deck size must be higher than '1'");
std::iota(deck.begin(), deck.end(), 1); // fills array from 1 to N
}
如果需要 constexpr,我会进行循环,因为 iota 尚未标记为 constexpr:
constexpr Jollo()
{
static_assert(N>1,"Jollo: deck size must be higher than '1'");
for (int i = 0 ; i < N ; ++i) {
deck[i] = i + 1;
}
}
推荐阅读
- python - 我不知道为什么我不断收到 AttributeError: 'tuple' object has no attribute 'size'
- php - 选择日期 flatpickr 后消失
- angular - 如何同时拥有 ReplaySubject 和 BehaviorSubject 功能
- python - 带有 while 循环验证的简单更改计算器
- amazon-web-services - 从 AWS SES 记录电子邮件集
- javascript - 如何用对象中提供的输入字段和值替换字符串中的占位符
- node.js - Node Express 在 Azure 应用服务中发送切片响应
- reactjs - jwtwebtoken 过期 reactjs
- javascript - Object(...)().signInUserWithEmailAndPassword 不是函数....尝试登录用户
- java - 两个相同的程序不同的输出?