首页 > 解决方案 > 使用从 1 到 N 模板参数的数字初始化 std 数组

问题描述

我有一个模板类,并想用参数中指定的std::array数字初始化它。这该怎么做?1N

#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;
}

标签: c++arrays

解决方案


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;
    }
}

推荐阅读