英文:
How to return array in C++ not a pointer?
问题
我知道如何返回一个指向数组第一个元素的指针,但我的问题是,如果可能的话,我应该如何返回实际的数组,而不是指向该数组的指针。
类似地,我应该如何通过引用传递数组给一个函数:
void print_arr(int (&arr)[3])
{
for (size_t i = 0; i < 3; ++i)
std::cout << arr[i] << ' ';
}
我想到了类似这样的东西:
int(&)[3] func(int (&arr)[3])
{
// 一些代码...
return arr;
}
但它不起作用。这里是在线编译器中的代码。
英文:
I know how to return a pointer which points to the first element of the array, but my question is how would I return actual array, not a pointer to that array if that is even possible.
Similarly to how would I pass array to a function by reference:
void print_arr(int (&arr) [3])
{
for(size_t i = 0; i < 3; ++i)
std::cout << arr[i] << ' ';
}
I thought something like this:
int(&)[3] func(int (&arr) [3])
{
// some code...
return arr;
}
But it doesn't work. Here is the code in online compiler.
答案1
得分: 0
你不能在C或C++中直接返回数组。一个方法是声明一个包含数组的struct
/union
来绕过这个问题。
union arrayint3 {
int i[3];
};
arrayint3 func(int(&arr)[3]) {
arrayint3 arr = {.i = {1, 2, 3}};
return arr;
}
你也可以返回一个std::array
。根据链接的问题和答案:
是否合法通过值返回
std::array
,像这样?std::array<int, 3> f() { return std::array<int, 3> {1, 2, 3}; }
是的,这是合法的。
英文:
You cannot 'return arrays' directly in C or C++. One way you can use to get around that is declare a struct
/union
containing the array.
union arrayint3 {
int i[3];
};
arrayint3 func(int(&arr)[3]) {
arrayint3 arr = {.i = {1, 2, 3}};
return arr;
}
You can also return an std::array
.
According to the linked Q&A:
> Is it legal to return std::array
by value, like so?
>
> std::array<int, 3> f() {
> return std::array<int, 3> {1, 2, 3};
> }
>
> Yes it's legal.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论