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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18938679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:20:50  来源:igfitidea点击:

Initialization of an array of structs in C++

c++c++11structinitializationc-strings

提问by JustKash

If I have a struct like below:

如果我有一个像下面这样的结构:

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

Is there a way for me to initialize an array of this structures. Perhaps like below:

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

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

Ultimately I would like to have a constantly declared array of structs inside a C++ class. How can this be done? Is it possible to have a privately declared member that is pre-initialized?

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

回答by Kerrek SB

Sure, you'd write it like this:

当然,你会这样写:

#include <string>
#include <vector>

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

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

Unless I'm misunderstanding and you actually just want numto count the number of elements. Then you should just have:

除非我误解了你实际上只想num计算元素的数量。那么你应该只需要:

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

And you can recover the element sizes with data[0].size(), data[1].size(), etc.

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



If everything is determined statically and you just want a compact reference, you still need to provide storage, but everything is virtually the same as in C:

如果一切都是静态确定的,而您只想要一个紧凑的引用,您仍然需要提供存储空间,但一切都与 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 } };

Since the size is std::distance(std::begin(a0), std::end(a0)), you could simplify the last part with a macro that just takes a0as an argument. And instead of handwriting Foo, you might just use std::pair<char const **, std::size_t>.

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

回答by Mats Petersson

You mean something like this:

你的意思是这样的:

// In some headerfile:

// 在一些头文件中:

class X
{
  private:
    static const MyStruct MY_STRUCTS[]; 
};

// in some .cpp file:

// 在一些 .cpp 文件中:

const X::MyStruct MY_STRUCTS[] = { { {"Hello"}, 1}, { "Other String"} , 3 } }; 

That assumes, however, that you have a char *str;, since char **str;requires a secondary variable to take the address off. Or, you could use std::vector<string>, and that would solve the problem.

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

回答by Dietmar Kühl

You can use something like

你可以使用类似的东西

class foo {
    MyStruct array[2];
public:
    foo()
        : array{ { "a", 1 }, { "b", 2 }}
    {
    }
};

assuming you struct's first member is actually char const*rather than char**as you initialization example suggests.

假设您struct的第一个成员实际上是char const*而不是char**您初始化示例所建议的那样。