[英]Iniitializing an array of unknown size
Is it possible to have a function that returns an array of variable size? 是否有可能返回一个可变大小数组的函数? My plan is to have the size of the returned array as the first member of the array (so ret_val[0] = # of members in ret_val).
我的计划是将返回数组的大小作为数组的第一个成员(因此ret_val [0] = ret_val中的成员数)。
The problem then becomes with initializing an array to the return value of that function. 然后问题就是将数组初始化为该函数的返回值。
int moves[] = target_function()
wouldn't possibly compile. int moves[] = target_function()
不可能编译。
Every one is telling you to use a vector, but nobody is showing you how to do that. 每个人都告诉你使用矢量,但没有人告诉你如何做到这一点。 Here's how:
这是如何做:
#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 );
}
You can return a pointer instead of an array: 您可以返回指针而不是数组:
int* moves = target_function();
But don't return a pointer to something you created on the stack as it will go out of scope when the function returns. 但是不要返回指向你在堆栈上创建的东西的指针,因为它会在函数返回时超出范围。 You can dynamically allocate the array on the heap.
您可以在堆上动态分配数组。
I would suggest not using such hacks. 我建议不要使用这样的黑客。 There is std::vector ready for you to use.
有std :: vector可供您使用。 If you really want to go this way, here's the code that does what you want:
如果你真的想这样,那么代码可以满足您的需求:
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;
Usually you would use a pointer to an dynamically allocated array: 通常,您将使用指向动态分配的数组的指针:
int* target_function() {
int result* = new int[123];
result[0] = 123;
return result;
}
int *moves = target_function();
std::cout << moves[0] << " moves" << std::endl;
That being said, generally it is more practical and less error prone to use a standard library container like std::vector<int>
instead. 话虽如此,通常使用标准库容器(如
std::vector<int>
)更实用,更不容易出错。 In C++ this is basically always the better choice than a raw array. 在C ++中,这基本上总是比原始数组更好的选择。
Such array cannot be an automatic variable. 这样的数组不能是自动变量。 It needs to be a pointer to a dynamically created array as Mark said.
Mark表示,它需要是一个指向动态创建数组的指针。
The short answer is that you can't return an array. 简短的回答是你不能返回数组。 You can return a pointer to dynamically allocated memory though:
您可以返回指向动态分配的内存的指针:
int* moves = target_function();
// do stuff with moves
delete[] moves;
The target_function()
will have to use new
to allocate the memory. target_function()
必须使用new
来分配内存。
Note that this is not ideal from a memory management point of view, because it's easy to forget to call delete[]
on the returned array. 请注意,从内存管理的角度来看,这并不理想,因为很容易忘记在返回的数组上调用
delete[]
。 Instead, consider returning a std::vector<int>
. 相反,请考虑返回
std::vector<int>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.