c++ - 如何在 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]) ?
解决方案
该函数被声明为返回一个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;
}
推荐阅读
- matlab - 用于组合文件夹中的 .fig 文件以生成视频/动画的 MATLAB 代码?
- mysql - 为每个成员返回顶部字段的 SQL 查询
- c# - Dev Express Extreme Grid - 通过 IF 条件添加列属性
- xpath - 在 Jmeter 中使用 Xpath 提取器捕获响应
- r - 如何从数据框中绘图?
- tensorflow - Tensorflow gradientTape 解释
- c++ - 关于模板等效/重新定义的 C++ 规则?
- scala - 如何从 var arg 列表创建无形 HMap
- java - 使用 Streams ( List ) 将嵌套的整数列表转换为二维数组
- > -> int[][])
- c++ - 如何解决这个问题 在 C++ 上使用 GTK+ 编程?