是否有可能返回一個可變大小的數組的函數?我的計劃是將返回數組的大小作爲數組的第一個成員(所以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