You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中如何用构造参数在初始化列表初始化std::array嵌套数组

你现有代码存在两个核心问题:

  1. std::array 是固定大小容器,尺寸必须是编译期可确定的常量,无法使用运行时传入的 size1、size2 作为尺寸参数
  2. 你给出的 std::array 声明缺少必需的尺寸模板参数,属于语法错误

针对你的需求,提供两种可行方案:

方案1:运行时动态确定尺寸(适配你当前的传参逻辑)

将嵌套 std::array 替换为嵌套 std::vector,即可支持运行时传入尺寸,同时实现所有pair初始化为0的需求:

#include <vector>
#include <cstdint>
#include <utility>

class MyClass {
protected:
    std::size_t size1;
    std::size_t size2;
    std::vector<std::vector<std::pair<std::uint64_t, std::uint64_t>>> items;
public:
    MyClass(): MyClass(1, 1) {}
    MyClass(std::size_t size1, std::size_t size2): 
        size1(size1), 
        size2(size2), 
        // 构造size1个外层vector元素,每个元素是size2个值为{0,0}的pair
        items(size1, std::vector<std::pair<std::uint64_t, std::uint64_t>>(size2, {0, 0}))
    {}
};

方案2:编译期固定尺寸,保留std::array实现

如果你的尺寸可以在编译期确定,将尺寸设置为类的模板参数即可:

#include <array>
#include <cstdint>
#include <utility>

template<std::size_t Size1, std::size_t Size2>
class MyClass {
protected:
    static constexpr std::size_t size1 = Size1;
    static constexpr std::size_t size2 = Size2;
    std::array<std::array<std::pair<std::uint64_t, std::uint64_t>, Size2>, Size1> items;
public:
    // 空花括号聚合初始化会自动将所有pair的两个字段都零初始化为0
    MyClass(): items{} {}
};

// 使用示例:声明尺寸为3*2的实例
MyClass<3, 2> obj;

内容的提问来源于stack exchange,提问作者jkang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:06:02