我现在正在为 Ludum Dare 编码,我试图创建一个单独的类,它会给我一个数组作为函数的返回类型。我设置了一个数组,但我不知道如何将返回类型设为数组,以便可以在主函数中使用它。我将如何返回一个数组并将 main.cpp 中的变量设置为该数组?
问问题
120 次
2 回答
1
这里有几个例子,每个都有自己的优点:
#include <iostream>
// C++11 #include <array>
#include <vector>
void myVectorFunc1(std::vector<int>& data)
{
for (unsigned i = 0; i < data.size(); ++i)
data[i] = 9;
data.push_back(1);
data.push_back(2);
data.push_back(3);
}
std::vector<int> myVectorFunc2(void)
{
std::vector<int> data;
data.push_back(1);
data.push_back(2);
data.push_back(3);
return data;
}
/* C++ 11
template<std::size_t S>
void myArrayFunc1(std::array<int, S>& arr)
{
for (auto it = arr.begin(); it != arr.end(); ++it)
*it = 9;
}
std::array<int,5> myArrayFunc2(void)
{
std::array<int,5> myArray = { 0, 1, 2, 3, 4 };
return myArray;
}
*/
int main(int argc, char** argv)
{
// Method 1: Pass a vector by reference
std::vector<int> myVector1(10, 2);
myVectorFunc1(myVector1);
std::cout << "myVector1: ";
for (unsigned i = 0; i < myVector1.size(); ++i)
std::cout << myVector1[i];
std::cout << std::endl;
// Method 2: Return a vector
std::vector<int> myVector2 = myVectorFunc2();
std::cout << "myVector2: ";
for (unsigned i = 0; i < myVector2.size(); ++i)
std::cout << myVector2[i];
std::cout << std::endl;
/* C++11
// Method 3: Pass array by reference
std::array<int, 3> myArray1;
std::cout << "myArray1: ";
myArrayFunc1(myArray1);
for (auto it = myArray1.begin(); it != myArray1.end(); ++it)
std::cout << *it;
std::cout << std::endl;
// Method 4: Return an array
std::cout << "myArray2: ";
std::array<int,5> myArray2 = myArrayFunc2();
for (auto it = myArray2.begin(); it != myArray2.end(); ++it)
std::cout << *it;
std::cout << std::endl;
*/
return 0;
}
于 2013-08-24T03:51:36.777 回答
1
# include <iostream>
int * func1()
{
int* array = (int *)malloc(sizeof(int) * 2);
array[0] = 1;
array[1] = 5;
return array;
}
int main()
{
int * arrayData = func1();
int len = sizeof(arrayData)/sizeof(int);
for (int i = 0; i < len; i++)
{
std::cout << arrayData[i] << std::endl;
}
}
请检查https://stackoverflow.com/a/5503643/1903116了解为什么不这样做。并引用该答案
函数不应具有类型数组或函数的返回类型,尽管它们可能具有类型指针或对此类事物的引用的返回类型。
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf第 159 页 - 第 6 节
于 2013-08-24T03:54:44.417 回答