[英]C++ How to return an array from a function?
I'm brand new to C++ and am having trouble trying to get a function (which takes an array) to return an array. 我是C ++的新手,我很难尝试获取一个函数(它接受一个数组)来返回一个数组。 The function is a very basic sorting algorithm for an array of integers of size 4. What i have is below: 该函数是一个非常基本的排序算法,适用于大小为4的整数数组。具体如下:
int[] sortArrayAscending(int arrayToSort[3]) {
int sortedArray[3];
sortedArray[0] = minOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[1] = lowerMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[2] = higherMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[3] = maxOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
return sortedArray;
}
I think i'm getting really confused with the syntax i need to use (the function calls to min, lower, higher, max all work fine. 我想我真的很困惑我需要使用的语法(函数调用min,lower,higher,max都可以正常工作。
I would really appreciate some help. 我真的很感激一些帮助。
Thank you 谢谢
EDIT2: Thank you for all the comments. EDIT2:感谢您的所有评论。 I have now solved it thanks to @Rook's and @Bob Yoplait's answers. 由于@ Rook和@Bob Yoplait的回答,我现在已经解决了这个问题。 The code is used is: 代码用于:
int* sortArrayAscending(int arrayToSort[4], int sortedArray[4]) {
sortedArray[0] = minOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[1] = lowerMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[2] = higherMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[3] = maxOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
return sortedArray;
}
int _tmain(int argc, _TCHAR* argv[])
{
int testNumbers[4] = {8,14,1,27};
int testSorted[4];
sortArrayAscending(testNumbers,testSorted);
for (int i = 0; i < 4; i++) {
cout << testSorted[i] << endl;
}
system("pause");
return 0;
}
Thank you for all your help - now time to lookup vectors! 感谢您的帮助 - 现在是时候查找矢量了!
PS I appreciate @Luchian Grigore's solution is most likely the best practise way of doing things, but that wasn't specifically my question PS我很欣赏@Luchian Grigore的解决方案很可能是最好的做法,但这不是我的问题
Me, I'd probably use std::array<int, 4>
if I was using a modern C++ compiler. 我,如果我使用现代的C ++编译器,我可能会使用std::array<int, 4>
。 Deals nicely with bounds checking and memory management and returning from/passing into functions. 很好地处理边界检查和内存管理以及从/传递到函数。 You can also use existing STL sort
mechanisms and functions upon it; 您还可以使用现有的STL sort
机制和功能; no need to reinvent the wheel! 无需重新发明轮子!
Now, in your case, 现在,在你的情况下,
int sortedArray[3];
is a local variable and you should never return a reference to it directly. 是一个局部变量,你永远不应该直接返回它的引用。 You could do something like : 你可以这样做:
int* sortedArray = new int[4];
// do stuff
return sortedArray;
(also note the size of the array, 4, not 3 in your case!) but in this case you have to remember to delete the array at some point in the future or your application will leak memory. (还要注意数组的大小,4,在你的情况下不是3!)但是在这种情况下你必须记得在将来的某个时候删除数组,否则你的应用程序将泄漏内存。
You can also pass in the array by reference, using an approach like 您也可以使用类似的方法通过引用传入数组
void sort_array(std::array<int, 4>& the_array);
or 要么
void sort_array(int** the_array)
and in these cases you can modify the array in place, or copy the answer into the argument when you're done sorting. 在这些情况下,您可以就地修改数组,或者在完成排序后将答案复制到参数中。
EDIT: After your edit, you, your function returns a pointer to an array. 编辑:编辑后,您的函数返回一个指向数组的指针。 Should work. 应该管用。
You can either return a pointer or a std::vector
. 您可以返回指针或std::vector
。
Note that in your code, you'd be running into undefined behavior, because sortedArray
goes out of scope at the end of the method, and the memory is freed. 请注意,在您的代码中,您将sortedArray
未定义的行为,因为sortedArray
在方法结束时超出范围,并释放内存。
I'd do this instead: 我会这样做:
std::vector<int> sortArrayAscending(int arrayToSort[4]) {
std::vector<int> sortedArray(4);
sortedArray.push_back( minOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]));
sortedArray.push_back( lowerMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]));
sortedArray.push_back( higherMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]));
sortedArray.push_back( maxOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]));
return sortedArray;
}
Actually, I wouldn't. 实际上,我不会。 I'd just use std::sort
instead of creating my own function, but that's just me. 我只是使用std::sort
而不是创建我自己的函数,但那只是我。
You are returning pointer to local variable, which leads to undefined behavior . 您正在返回指向局部变量的指针,这会导致未定义的行为 。 sortedArray
is statically allocated array with automatic storage duration, which means that memory where it resides is being freed once you leave the scope of the function. sortedArray
是静态分配的数组,具有自动存储持续时间,这意味着一旦离开函数范围,它所驻留的内存将被释放。
You should allocate it dynamically by using new[]
or even better: use std::vector
instead. 你应该使用new[]
甚至更好地动态分配它:使用std::vector
代替。 If you choose to allocate it by using new[]
, don't forget to free it by calling delete[]
when you don't need this memory anymore. 如果您选择使用new[]
进行分配,请不要忘记在不再需要此内存时通过调用delete[]
来释放它。
Also note that int sortedArray[3];
还要注意int sortedArray[3];
declares an array of size of 3 elements indexed from 0
to 2
. 声明一个从0
到2
索引的3个元素的数组。 If you access 4th element of the array whose size is 3 (if you access the memory "past the last element of the array object" ), the behavior is undefined as well. 如果访问大小为3的数组的第4个元素(如果访问内存“超过数组对象的最后一个元素” ), 则行为也是未定义的 。
As this is C++, suggest using a std::vector<int>
instead: 由于这是C ++,建议使用std::vector<int>
:
std::vector<int> sortArrayAscending(int arrayToSort[3]) {
std::vector<int> sortedArray(4); // Note 4, not 3.
sortedArray[0] = ...;
sortedArray[1] = ...;
sortedArray[2] = ...;
sortedArray[3] = ...;
return sortedArray;
}
Note there are several algorithms already available that will perform some of the tasks that you appear to be performing: 请注意,已有几种算法可用于执行您似乎正在执行的某些任务:
Use Boost::Array (or std::array in C+11) that provides proper value semantic to C array. 使用Boost :: Array(或C + 11中的std :: array)为C数组提供适当的值语义。
boost::array<int,4> sortArrayAscending(boost::array<int,4>7 arrayToSort)
{
boost::array<int,4> sortedArray;
sortedArray[0] = minOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[1] = lowerMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[2] = higherMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[3] = maxOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
return sortedArray;
}
It is not like in Java 它与Java不同
Either you pass sortedArray as a parameter to the func 您将sortedArray作为参数传递给func
int* sortArrayAscending(int* arrayToSort, int* sortedArray) {
sortedArray[0] = minOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[1] = lowerMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[2] = higherMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[3] = maxOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
return sortedArray;
}
void toto() {
int array[4]; // and fill values...
int sortedArray[4];
sortArrayAscending(array, sortedArray);
}
or 要么
int* sortArrayAscending(int* arrayToSort) {
int* sortedArray = new int[4];
sortedArray[0] = minOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[1] = lowerMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[2] = higherMidOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
sortedArray[3] = maxOfFour(arrayToSort[0],arrayToSort[1],arrayToSort[2],arrayToSort[3]);
return sortedArray;
}
and then you need to delete the returned array in the second case. 然后你需要在第二种情况下删除返回的数组。
Arrays are always passed by reference to any function in C++. 数组总是通过引用传递给C ++中的任何函数。 So, just pass your array to the function. 所以,只需将数组传递给函数即可。 Your original array would get sorted and you can then use it in your program. 您的原始数组将被排序,然后您可以在程序中使用它。 I believe there is no need to return the array explicitly. 我相信没有必要明确地返回数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.