【问题标题】:Vector of arrays of fixed size decided at runtime固定大小的数组向量在运行时决定
【发布时间】:2016-12-06 16:52:07
【问题描述】:

我正在尝试做这样的事情:

int x=128, y=256;
std::vector<std::array<float,x*y>> codes;

显然这是错误的,而这是正确的:

std::vector<std::array<float,128*256>> codes;

第一个问题的一个解决方案可能是使用如下宏:

#define x 128
#define y 256
...
std::vector<std::array<float,x*y>> codes;

但我想知道在运行时是否有另一种解决方案,而不是在编译时。 注意不必使用std::array,我需要std::vectorx*y 元素的数组(或其他)。

【问题讨论】:

    标签: c++ arrays vector


    【解决方案1】:

    尝试使用const

    const int x = 128;
    const int y = 256;
    ...
    std::vector<std::array<float,x*y>> codes;
    

    您的第一个代码中的问题在于 xy 不是常量,因此编译器无法依赖它们的值在运行时不会改变这一事实,因此无法确定编译时的模板参数值。

    【讨论】:

    • 我可以建议constexpr吗?这样,如果您尝试从运行时值中获取 xy,您将在此时收到编译器投诉,而不是在实例化 codes 时。
    • 瞧,成功了!谢谢!无论如何,既然xy 是由用户在运行时决定的,我们是否可以在不初始化它们的情况下声明它们并在第二个时刻(当用户插入值时,即128 和256)?跨度>
    • @user975989 同意constexpr 在这里可能更好。手头上没有新的编译器要检查。
    • @justHelloWorld 要创建一个在编译时大小未知的数组,您不能使用std::array。考虑改用std::vectorstd::vector 有一个很棒的构造函数,它允许您指定要填充的大小和值:vector&lt;vector&lt;float&gt;&gt; codes(size1, vector&lt;float&gt;(size2, 0))
    • @user975989 对不起,你能再解释一下为什么constexpr 应该更好吗?第一次见!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多