如何在C ++中返回结构?

时间:2019-09-22 07:20:38

标签: c++

我正在给公司的编码面试测试(在mettl.com上),这就是问题所在--

  

给出一个由“ n”个整数组成的数组,将“ 2”添加到该数组的每个元素中并返回该数组。

这是他们的代码格式(我无法更改其格式,我只能在函数内部编写代码。而且,我不必读取输入,它已经通过函数传递,也没有“ main-功能”)。

这是C ++中的代码:

#include<bits/stdc++.h>
using namespace std;
//Read only region starts, you cannot change the code here
//Assume following return types when writing code for this question

struct Result{
    Result() : output(){};
    int output1[100];
};
Result arrange(int input1, int input2[])
{
    //Read only region end...now...you can write whatever you want 
    int n;
    n=input1;
    int i=0;
    int a[n];
    while(i<n)
    {
        a[i]=input2[i]+2;
        i++;
    }

//...now..I am super confused...how do I return the array 'a' to result structure??
//I have very less idea about structures and objects in C++

}

我的答案在数组-'a'中,但我不知道如何将其返回到结构(output1 [100])?

3 个答案:

答案 0 :(得分:1)

要回答这个问题,请在函数中创建一个struct对象(“ Result R;”),并使用其成员output1数组复制到数组而不是数组“ a”(“ R.output1 [i] = ... ;”)。因此,只需删除“ a”数组并替换为struct对象的output1。然后返回该struct对象。

答案 1 :(得分:1)

该函数声明为返回Result结构。因此,该函数需要创建该结构的实例才能返回它。并且由于该结构中已经包含一个数组,因此您无需创建自己的数组,只需填写一个已经存在的数组即可。

尝试一下:

#include <bits/stdc++.h>
using namespace std;
//Read only region starts, you cannot change the code here
//Assume following return types when writing code for this question

struct Result{
    Result() : output1(){};
    int output1[100];
};
Result arrange(int input1, int input2[])
{
    //Read only region end...now...you can write whatever you want

    Result res;
    for(int i = 0; i < input1 && i < 100; ++i)
    {
        res.output1[i] = input2[i] + 2;
    }

    return res;
}

答案 2 :(得分:-1)

结构可以通过其对象传递给功能,因此将结构传递给功能或将结构对象传递给功能是相同的,因为结构对象代表结构。与普通变量一样,结构变量(结构对象)可以按值或按引用/地址传递。