首页 > 解决方案 > 如何在 C++ 中返回结构?

问题描述

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

给定一个包含“n”个整数的数组,将“2”添加到数组的每个元素并返回该数组。

这是他们的代码格式(我不能改变他们的格式,我可以在函数内部编写代码。另外,我不必读取输入,它已经通过函数传递,也没有“主函数”允许)。

以下是 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]) ?

标签: c++

解决方案


该函数被声明为返回一个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;
}

推荐阅读