简体   繁体   English

C ++结构初始化数组

[英]C++ Array of struct initialization

I am not really used to coding in C++ and this probably is a simple issue that I am not able to get the correct syntax of. 我不太习惯用C ++进行编码,这可能是一个简单的问题,我无法获得正确的语法。

What I am basically trying to achieve is that, from one method where I declare an array of a struct (size not specified), I call a method where I pass this array. 我基本上想要实现的是,从一个我声明一个结构数组(未指定大小)的方法中,我调用一个传递此数组的方法。 The method should initialize the values of the array. 该方法应初始化数组的值。 I tried to get a simple code working but getting errors. 我试图使一个简单的代码正常工作,但出现错误。 The following piece of code gives me a compilation error. 下面的代码给了我一个编译错误。 Can someone point out how to achieve this? 有人可以指出如何实现这一目标吗?

struct ABC
{
int a;
int b;
};

void test(ABC * a)
{
a[] = {{2,3},{4,5}};
}

int main() {
    ABC arr[2];
    test(arr);
}     

EDIT: 编辑:
The following works, but I would like the initialization to work in one line. 下面的作品,但我希望初始化工作在一行中。

struct ABC
{
int a;
int b;
};

void test(ABC *a)
{
a[0].a = 2;
a[0].b = 3;
a[1].a = 4;
a[1].b = 5;
}

int main() {
    ABC arr[2];
    test(arr);
}

You could use a setup like this, making use of the C++ standard library. 您可以使用C ++标准库这样的设置。 Compile it with the -std=c++11 flag to allow for the initialization I did in the push_back : 使用-std=c++11标志对其进行编译,以允许我在push_back进行的初始化:

#include <vector>
#include <iostream>

struct ABC
{
    int a;
    int b;
};

void test(std::vector<ABC>& a)
{

    a.push_back({2,3});
    a.push_back({4,5});
}

int main()
{
    std::vector<ABC> arr;
    test(arr);

    // Test the outcome...
    std::cout << "The size is: " << arr.size() << std::endl;
    for (ABC& a : arr)
        std::cout << "Element (" << a.a << "," << a.b << ")" << std::endl;

    return 0;
}

Initialize each struct accessing its index in a array. 初始化每个结构访问它的索引在a阵列。

void test(ABC * a)
{
    a[0] = {2,3};
    a[1] = {4,5};
    ...

This way {{2,3},{4,5}}; 这样{{2,3},{4,5}}; will work on initialization, ie 将在初始化上工作,即

ABC arr[2] = {
    {2,3},
    {4,5}
};

You have to first find out the actual size of the array and then iterate to initialize it. 您必须首先找出数组的实际大小,然后进行迭代以对其进行初始化。

Will not work, see below 无效,请参见下文

void test(ABC* a) {        
    int value=2;
    for (int i=0;i++;i<sizeof(a)/sizeof(ABC)) {
        a[i].a=value;
        a[i].b=value+1;
        value+=2; } }

I am not 100% sure the sizeof(a) will work in giving you the size of the array. 我不是100%确定sizeof(a)是否可以为您提供数组的大小。 If that does not work you will have to pass the size of the array as a parameter: 如果这样不起作用,则必须将数组的大小作为参数传递:

void test(ABC* a, int elements) {        
    int value=2;
    for (int i=0;i++;i<elements) {
        a[i].a=value;
        a[i].b=value+1;
        value+=2; } }

int main() {
    ABC arr[2];
    test(arr,2); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM