Return an array in c++

前端 未结 11 2105
半阙折子戏
半阙折子戏 2021-01-02 12:14

Suppose I have an array

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

I have the function as

 int& function(int arr[])
 {
//         


        
相关标签:
11条回答
  • 2021-01-02 12:34

    You're returning a reference to an int, not a reference to an array.

    You want :

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

    That said, as others already said, that's not good practice.

    0 讨论(0)
  • 2021-01-02 12:37

    I think your best bet is to return it as a pointer to an array. Here is an example:

    {
       ...
       int newLength = 0;
       int* arr2 = ChangeArray(arr, length, newLength);
       ...
       delete[] arr2;
    }
    
    int* ChangeArray(int arr[], int length, int& newLength)
    {
       // reversing the number - just an example
       int* newArr = new int[length];
       for(int i = 0; i < length; i++)
       {
          newArr[i] = arr[length-i-1];
          newLength++;
       }
       return newArr;
    }
    
    0 讨论(0)
  • 2021-01-02 12:39

    Use std:: vector like this.

    std::vector<int> function(const std::vector<int>& arr)
    {
      return arr;
    }
    

    An array like

    int arr[] = {...};
    

    is not useful to be returned from a function because its not able to copy itself.

    0 讨论(0)
  • 2021-01-02 12:40

    if not necessary, don't use it. you can just pass a reference of an array, such as:

    void foo(std::vector<int> &v) {
        for (int i = 0; i < 10; ++ i) {
            v.push_back(i);
        }
    }
    

    if you use:

    std::vector<int> foo() {
        std::vector<int> v;
        for (int i = 0; i < 10; ++ i)
            v.push_back(i);
    
        return v;
    }
    

    there'll be a copy process of the container, the cost is expensive.

    FYI: NRVO maybe eliminate the cost

    0 讨论(0)
  • 2021-01-02 12:45

    The semantics of array passing and return can be quite confusing. Use a std::vector instead.

    0 讨论(0)
提交回复
热议问题