如何从函数返回一个数组? [英] How to return an array from a function?

查看:102
本文介绍了如何从函数返回一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从一个方法返回一个数组,我必须声明是如何呢?

  INT []测试(无效); //?


解决方案

为int *测试();

但它会越C ++使用向量:

的std ::矢量< INT>测试();

修改结果
我要澄清一些点。既然你提到的C ++,我会去新[] 删除[] 运营商,但它与同的malloc /免费的。

在第一种情况下,你会写是这样的:

 为int *测试(){
    返回新INT [size_needed]
}

但由于你的函数的客户并不真正知道你正在返回数组,althought他/她可以安全地为通话unallocate它的大小,删除[] <这不是一个好主意/ code>。

 为int * theArray =测试();
用于(为size_t我;我&LT; ???; ++ I){//我不知道什么是数组大小!
    // ...
}
删除[] theArray; // 好。

有一个更好的签名是这样的:

 为int *测试(为size_t&安培; ARRAYSIZE){
    ARRAY_SIZE = 10;
    返回新INT [ARRAY_SIZE]
}

和您的客户端code现在会:

 为size_t theSize = 0;
为int * theArray =测试(theSize);
用于(为size_t我;我&LT; theSize ++ I){//现在我可以放心地遍历数组
    // ...
}
删除[] theArray; //还OK。

由于这是C ++,`的std ::矢量&lt; T>为 解决方案,恕我直言:

 的std ::矢量&lt;&INT GT;试验(){
    的std ::矢量&lt;&INT GT;载体(10);
    返回向量;
}

现在你不必叫删除[] ,因为它会由对象处理,你可以放心地使用迭代的:

 的std ::矢量&lt;&INT GT; V =试验();
的std ::矢量&lt;&INT GT;:迭代它= v.begin();
为(;!它= v.end(); ++吧){
   //做你的事
}

更容易和安全。

How can I return an array from a method, and how must I declare it?

int[] test(void); // ??

解决方案

int* test();

but it would be "more C++" to use vectors:

std::vector< int > test();

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];
}

but it's not a nice idea because your function's client doesn't really know the size of the array you are returning, althought he/she can safely unallocate 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.

A better signature would be this one:

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.

Since this is C++, `std::vector< T > is the solution, IMHO:

std::vector<int> test() {
    std::vector<int> vector(10);
    return vector;
}

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
}

easier and safer.

这篇关于如何从函数返回一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆