Return an array in c++

前端 未结 11 2174
半阙折子戏
半阙折子戏 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:40

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

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

    if you use:

    std::vector foo() {
        std::vector 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

提交回复
热议问题