search

Home  >  Q&A  >  body text

c++ - 数组的引用作为返回值,为什么报错?

初学者,但在网上找不到答案。。有哪位好心人能帮我看看,不甚感激

template<int SIZE> 
int(&a)[SIZE] insertSort(int(&arr)[SIZE])
{
    return arr;
};
void main()
{
    int arr[] = {2,4,56,65,3,6,9,4,3,5,8,4,2,1,0};
    insertSort(arr);//提示找不到insertSort函数,如果将函数的返回值修改一下,编译就能通过
}
伊谢尔伦伊谢尔伦2803 days ago549

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 11:58:00

    There is also a problem with the way you write the function. I found an answer on stackoverflow. I can test it myself and run it

    template<size_t n>
    int (&insertSort(int (&arr)[n]))[n]
    {
        return arr;
    }
    

    http://stackoverflow.com/a/2302395

    By the way, try not to do this

    1. This kind of code is difficult to read, and this template is not very scientific. A new n will generate a new function
    2. If you want to return an array, you can use a pointer, but try not to do this, because allocating memory within a function can easily cause memory leaks (unless it only allocates memory)
    3. The correct way to return an array is to pass a pointer to allocated memory, like thisvoid sort(const int *arr, int *sortedArr)
    4. More recommendedvector

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:58:00

    The first line is like this: template<int SIZE>

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 11:58:00

    Since C++ is used, type safety can be achieved here without using pointers. As @wangdai said vector. As for returns, assignments, etc., you don’t have to worry about them. The simplest way is to use out参数

    directly.
    #include <vector>
    #include <utility>
    #include <iostream>
    
    template<class t>
    void insert_sorter(std::vector<t>& array /* out */) {
        /// ...
        array[3] = 0xff;
    }
    
    int main() {
        std::vector<int> array = {1, 2, 3, 4, 5};
        insert_sorter(array);
        std::cout << array.at(3) << std::endl;
    }
    

    Of course, if you have to go back to achieve the high-big effect, then do this

    #include <vector>
    #include <utility>
    #include <iostream>
    
    template<class t>
    std::vector<t> insert_sorter(std::vector<t>& array) {
        /// ...
        array[3] = 0xff;
    
        /// move 语义不会重复拷贝array的data数据
        return std::move(array);
    }
    
    int main() {
        std::vector<int> array = {1, 2, 3, 4, 5};
        /// 这里使用了完美的移动赋值操作,是不是比`C`的方式顺眼多了
        /// 不过要记住array后面不能再使用了
        std::vector<int> ret = insert_sorter(array);
        std::cout << ret.at(3) << std::endl;
    }
    

    Honestly, the orthodox C++ way should be

    /// 按stl的范式实现自己的sort
    std::sort(s.begin(), s.end(), [](int a, int b) {
        return b < a;   
    });
    

    reply
    0
  • Cancelreply