是否有可能返回一个可变大小的数组的函数?我的计划是将返回数组的大小作为数组的第一个成员(所以ret_val [0] = ret_val中成员的数量)。初始化未知大小的数组
问题就出现在初始化一个数组到该函数的返回值上。 int moves[] = target_function()
不可能编译。
是否有可能返回一个可变大小的数组的函数?我的计划是将返回数组的大小作为数组的第一个成员(所以ret_val [0] = ret_val中成员的数量)。初始化未知大小的数组
问题就出现在初始化一个数组到该函数的返回值上。 int moves[] = target_function()
不可能编译。
您可以返回一个指针,而不是一个数组:
int* moves = target_function();
但不要返回一个指向你在栈上创建的东西,因为它会走出去的范围时,函数返回。您可以在堆上动态分配数组。
对不起,但我-1不好的做法。该函数应该返回一个'std :: vector'。 – GManNickG 2010-10-30 21:43:10
简短的回答是你不能返回一个数组。您可以返回一个指向动态分配的内存,但:
int* moves = target_function();
// do stuff with moves
delete[] moves;
的target_function()
将不得不使用new
分配内存。
请注意,从内存管理的角度来看,这并不理想,因为很容易忘记在返回的数组上调用delete[]
。相反,请考虑返回std::vector<int>
。
我会建议不要使用这样的黑客。有std :: vector准备好供您使用。如果你真的想要走这条路,这里的代码,你想要做什么:
int *allocate(int size)
{
int *res = new int[size];
res[0] = size;
return res;
}
// Prints "Yes, it's 42":
int *myArray = allocate(42);
if (myArray[0] == 42)
std::cout << "Yes, it's 42!" << std::endl;
通常你会使用一个指向动态分配的数组:
int* target_function() {
int result* = new int[123];
result[0] = 123;
return result;
}
int *moves = target_function();
std::cout << moves[0] << " moves" << std::endl;
话虽这么说,一般是更实际的,并且不太容易使用像std::vector<int>
这样的标准库容器。在C++中,这基本上总是比原始数组更好的选择。
每个人都告诉你使用矢量,但没有人告诉你如何做到这一点。方法如下:
#include <vector>
std::vector<int> target_function(int size)
{
std::vector<int> v(size);
v[0] = size;
return v;
}
int main()
{
std::vector<int> moves = target_function(my_favorite_int);
}
谢谢你,+1只是建议一个向量,而不是这种喋喋不休的废话。有什么要说的:“这是代码,哦,顺便说一句,糟糕的代码不会使用它。”? – GManNickG 2010-10-30 21:43:45
为什么不使用'std :: vector'? – kennytm 2010-10-30 18:54:54
同意,使用std :: vector - 这就是它的用途。 – Puppy 2010-10-30 18:57:25
在编译时必须知道C++中数组变量的大小。堆栈中的数组无法从运行时变量大小初始化。肯尼是对的,这是'vector'的意思。 – 2010-10-30 18:59:51