在C ++中初始化结构数组 [英] Initialization of an array of structs in C++

查看:87
本文介绍了在C ++中初始化结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有如下结构:

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
    },
};

最终我想在C ++类中拥有一个不断声明的结构体数组。如何才能做到这一点?

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?

推荐答案

当然,您可以这样写:

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 }
                        };

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

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

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

您可以使用 data [0] .size( ) data [1] .size()等。

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

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:

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>

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

这篇关于在C ++中初始化结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆