返回数组在C + + [英] Return an array in c++

查看:81
本文介绍了返回数组在C + +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组

  INT ARR [] = {...};
ARR =功能(ARR);

我有功能

  INT和放大器;功能(INT ARR [])
 {
//将code休息
        返回ARR;
 }

什么错误我在做在这里??


解决方案

  INT和放大器;功能(INT ARR [])

在此功能ARR是一个指针,而且也没有办法再次打开它到一个数组。这是一样的。

  INT和放大器;功能(INT * ARR)


  INT ARR [] = {...};
ARR =功能(ARR);

假设功能设法返回数组的引用,这仍然是行不通的。您不能分配到一个数组。在最好的情况,你可以将结果绑定到X int数组的引用(使用一个typedef,因为语法将变得非常难看,否则):

 的typedef INT ten_ints [10];ten_ints&安培;富(ten_ints&安培; ARR)
{
   // ..
   返回ARR;
}诠释的main()
{
    INT ARR [10];
    ten_ints&安培; arr_ref = foo的(ARR);
}

但是,它是完全不清楚什么在你的问题中code被认为能实现。您对自己的功能阵列的任何变化将是可见的来电者,因此没有理由去企图返回数组或分配回原来的阵列。


如果你想有一个固定大小的数组,可以分配给和按值传递(与正在复制的内容),还有的std :: tr1 ::阵列(或的boost ::阵列)。 的std ::矢量也是一种选择,但是这是一个动态数组,所以不是完全等效。

Suppose I have an array

int arr[] = {...};
arr = function(arr);

I have the function as

 int& function(int arr[])
 {
//rest of the code
        return arr;
 }

What mistake am I making over here??

解决方案

 int& function(int arr[])

In this function arr is a pointer, and there's no way to turn it back to an array again. It's the same as

int& function(int* arr)


int arr[] = {...};
arr = function(arr);

Assuming the function managed to return a reference to array, this still wouldn't work. You can't assign to an array. At best you could bind the result to a "reference of an array of X ints" (using a typedef because the syntax would get very ugly otherwise):

typedef int ten_ints[10];

ten_ints& foo(ten_ints& arr)
{
   //..
   return arr;
}

int main()
{
    int arr[10];
    ten_ints& arr_ref = foo(arr);
}

However, it is completely unclear what the code in your question is supposed to achieve. Any changes you make to the array in function will be visible to the caller, so there's no reason to try to return the array or assign it back to the original array.


If you want a fixed size array that you can assign to and pass by value (with the contents being copied), there's std::tr1::array (or boost::array). std::vector is also an option, but that is a dynamic array, so not an exact equivalent.

这篇关于返回数组在C + +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆