用C++初始化结构数组

Aka*_*ash 0 c++ struct initialization c-strings c++11

如果我有一个如下所示的结构:

typedef struct MyStruct {
    char **str;
    int num;    
} MyStruct;
Run Code Online (Sandbox Code Playgroud)

有没有办法让我初始化这个结构的数组.也许如下:

const MyStruct MY_STRUCTS[] = {
    {
        {"Hello"}, 
        1
    },
    {
        {"my other string"}, 
        3
    },
};
Run Code Online (Sandbox Code Playgroud)

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

Ker*_* SB 10

当然,你会这样写:

#include <string>
#include <vector>

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

MyStruct const data[] = { { { "Hello", "World" }, 1 }
                        , { { "my other string" }, 3 }
                        };
Run Code Online (Sandbox Code Playgroud)

除非我误解,你实际上只是想num计算元素的数量.然后你应该有:

std::vector<std::string> data[] = { { "Hello" }
                                  , { "my", "other", "string" }
                                  };
Run Code Online (Sandbox Code Playgroud)

你可以恢复与该元件的尺寸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 } };
Run Code Online (Sandbox Code Playgroud)

由于大小是std::distance(std::begin(a0), std::end(a0)),您可以使用仅a0作为参数的宏来简化最后一部分.而不是手写Foo,你可能只是使用std::pair<char const **, std::size_t>.


Mat*_*son 5

你的意思是这样的:

// 在一些头文件中:

class X
{
  private:
    static const MyStruct MY_STRUCTS[]; 
};
Run Code Online (Sandbox Code Playgroud)

// 在一些 .cpp 文件中:

const X::MyStruct MY_STRUCTS[] = { { {"Hello"}, 1}, { "Other String"} , 3 } }; 
Run Code Online (Sandbox Code Playgroud)

但是,这假设您有一个char *str;, 因为char **str;需要一个辅助变量来取消地址。或者,您可以使用std::vector<string>, 这样就可以解决问题。