如何从函数返回数组? [英] How to return an array from a function?
问题描述
如何从方法返回一个数组,我必须如何声明它?
How can I return an array from a method, and how must I declare it?
int[] test(void); // ??
推荐答案
int* test();
但是使用向量会是更多的 C++":
but it would be "more C++" to use vectors:
std::vector<国际 >test();
编辑
我会澄清一些观点.既然你提到了 C++,我会用 new[]
和 delete[]
操作符,但它与 malloc/free 相同.
EDIT
I'll clarify some point. Since you mentioned C++, I'll go with new[]
and delete[]
operators, but it's the same with malloc/free.
在第一种情况下,您将编写如下内容:
In the first case, you'll write something like:
int* test() {
return new int[size_needed];
}
但这不是一个好主意,因为您的函数的客户端并不真正知道您返回的数组的大小,尽管客户端可以通过调用 delete[]
安全地释放它.
but it's not a nice idea because your function's client doesn't really know the size of the array you are returning, although the client can safely deallocate it with a call to delete[]
.
int* theArray = test();
for (size_t i; i < ???; ++i) { // I don't know what is the array size!
// ...
}
delete[] theArray; // ok.
更好的签名是这个:
int* test(size_t& arraySize) {
array_size = 10;
return new int[array_size];
}
您的客户端代码现在是:
And your client code would now be:
size_t theSize = 0;
int* theArray = test(theSize);
for (size_t i; i < theSize; ++i) { // now I can safely iterate the array
// ...
}
delete[] theArray; // still ok.
由于这是 C++,std::vector
是一种广泛使用的解决方案:
Since this is C++, std::vector<T>
is a widely-used solution:
std::vector<int> test() {
std::vector<int> vector(10);
return vector;
}
现在您不必调用 delete[]
,因为它将由对象处理,您可以安全地迭代它:
Now you don't have to call delete[]
, since it will be handled by the object, and you can safely iterate it with:
std::vector<int> v = test();
std::vector<int>::iterator it = v.begin();
for (; it != v.end(); ++it) {
// do your things
}
哪个更简单更安全.
这篇关于如何从函数返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!