在C ++中初始化结构数组

JustKash

如果我有如下结构:

typedef struct MyStruct {
    char **str;
    int num;    
} MyStruct;

有没有一种方法可以初始化此结构的数组。也许像下面这样:

const MyStruct MY_STRUCTS[] = {
    {
        {"Hello"}, 
        1
    },
    {
        {"my other string"}, 
        3
    },
};

最终,我希望在C ++类中有一个不断声明的结构数组。如何才能做到这一点?是否可以有一个预先初始化的私有声明成员?

克瑞克(Kerrek SB)

当然,您可以这样写:

#include <string>
#include <vector>

struct MYStruct
{
     std::vector<std::string> str;
     int num;
};

MyStruct const data[] = { { { "Hello", "World" }, 1 }
                        , { { "my other string" }, 3 }
                        };

除非我误会了,否则您实际上只想num计算元素的数量。然后,您应该只有:

std::vector<std::string> data[] = { { "Hello" }
                                  , { "my", "other", "string" }
                                  };

你可以恢复与该元件的尺寸data[0].size()data[1].size()等等。


如果所有内容都是静态确定的,并且您只需要一个紧凑的引用,则仍然需要提供存储,但是实际上所有内容都与C中的相同:

namespace    // internal linkage
{
    char const * a0[] = { "Hello" };
    char const * a1[] = { "my", "other", "string" };
    // ...
}

struct Foo
{
    char const ** data;
    std::size_t len;
};

Foo foo[] = { { a0, 1 }, { a1, 3 } };

由于大小为std::distance(std::begin(a0), std::end(a0)),您可以使用仅a0作为参数的宏来简化最后一部分Foo除了手写以外,您还可以使用std::pair<char const **, std::size_t>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章