注册 登录
编程论坛 C++教室

二维结构体数组部分初始化问题

纯蓝之刃 发布于 2020-08-16 10:24, 2098 次点击
程序代码:
class AA
{
struct Cell
    {
        int x;
        int y;
        String value;
    };  
struct Cell m_cell[3][20];   
}


在AA类里定义struct Cell类型的结构体,如何在m_cell[3][20]初始化的时候对结构体里部分数据进行赋值,不是那种一个变量一个变量赋值的方式。m_cell[3][20]为AA类中的全局变量。
4 回复
#2
Jonny02012020-08-16 14:15
如果用数组感觉没什么太好的方法, String 大概率不是 POD 类型, 所以不能直接 memset
程序代码:
class Foo {
    struct C {
        int x, y;
        std::string value;
    };
    C m_cell[3][20];
private:
    void m_cell_init();
public:
    Foo() : m_cell {} {
        this->m_cell_init();
    }
};


用 std::vector 配合 C++ 11 的列表初始化可以做到每一个维度的前 n 个初始化
程序代码:
class Foo {
    struct C {
        int x, y;
        std::string value;
        C(int, int, const std::string &);
    };
    vector<vector<C>> m_cell;
public:
    Foo() : m_cell {
        {C(1, 1, "第一维度")},
        {C(2, 1, "第二维度")}, {C(2, 2, "第二维度")},
        {}      //第三维度为空
    } {}
};
#3
纯蓝之刃2020-08-16 20:07
回复 2楼 Jonny0201
Foo() : m_cell {
        {C(1, 1, "第一维度")},
        {C(2, 1, "第二维度")}, {C(2, 2, "第二维度")},
        {}      //第三维度为空
    } {}
没太理解这个意思。
假如我需要定义数组的[0][0],[0][1],[0][2],[0][3],[1][0],[1][1],[2][0],[2][1]需要怎么写?
#4
纯蓝之刃2020-08-16 20:19
回复 3楼 纯蓝之刃
struct Cell
    {
        int x;
        int y;
        QString value;
    };
    struct Cell m_cell[4][20]={ {{8,0,"数量"},{0,0,"原文件路径"},{0,1,"原文件名"},{0,2,"目标文件路径"},{0,3,"目标文件名"},{1,0,"例:C:/abc"},{1,1,"def.txt"},{1,2,"C:/abc"},{1,3,"hij.txt"}},
                                {{6,0,"数量"},{0,0,"原文件路径"},{0,1,"原文件名"},{0,2,"目标文件名"},{1,0,"例:C:/abc"},{1,1,"def.txt"},{1,2,"hij.txt"}},
                                {{6,0,"数量"},{0,0,"文件名"},{0,1,"原文件路径"},{0,2,"目标文件路径"},{1,0,"例:def.txt(支持*.txt和*.*匹配)"},{1,1,"C:/abc"},{1,2,"C:/def"}},
                                {{8,0,"数量"},{0,0,"文件路径"},{0,1,"文件名"},{0,2,"查找字符"},{0,3,"替换字符"},{1,0,"例:C:/abc"},{1,1,"def.txt"},{1,2,"qaz"},{1,3,"wsx"}}};

我按照c的方法这样实现了。
#5
Jonny02012020-08-16 23:13
回复 3楼 纯蓝之刃
程序代码:
class Foo {
    struct C {
        int x, y;
        std::string value;
        C(int, int, const std::string &);
    };
    vector<vector<C>> m_cell;
public:
    Foo() : m_cell {
        {C(0, 0, "第一维度")}, {C(0, 1, "第一维度")}, {C(0, 2, "第一维度")}, {C(0, 3, "第一维度")},
        {C(1, 0, "第二维度")}, {C(1, 1, "第二维度")},
        {C(2, 0, "第三维度"), {C(2, 1, "第三维度"),
    } {}
};


参考 C++ 11 列表初始化
1