首页 > 解决方案 > 智能指针二维数组作为参数

问题描述

我试图通过发送一个通过智能指针创建的二维数组作为参数来从函数中返回第三高的数字,但问题是,我不知道该怎么做。我一直在互联网上寻找可能的解决方案,但似乎找不到,这就是我所做的,

int thirdhigh(int array[4][5])
{}

int main()
{
    std::shared_ptr<std::shared_ptr<int[]>[]>array(new std::shared_ptr<int[]>[4]);//creates an array of pointers

    //creates an array of size 5 and sends it addressess to the previous created array of pointers
    for (int rows{ 0 }; rows < 4; ++rows) {
        array[rows] = std::shared_ptr<int[]>(new int[5]);
    }

    //assigns random values to the 2D array created from 1-100
    for (int r{ 0 }; r < 4; ++r) {
        for (int c{ 0 }; c < 5; ++c) {
            array[r][c] = ((rand() % 100) + 1);
        }
    }

    //Shows the values assigned to the 2D array
    for (int r{ 0 }; r < 4; ++r) {
        for (int c{ 0 }; c < 5; ++c) {
            std::cout << array[r][c] << "\t";
        }
        std::cout << std::endl;
    }
    //Returns the third highest number
    thirdhigh(array[4][5]);
}

此外,我仅在尝试学习时才需要使用智能指针。任何的意见都将会有帮助。谢谢!

标签: c++functionc++11multidimensional-arraysmart-pointers

解决方案


std::shared_ptr<std::shared_ptr<int[]>[]>是您要传递给函数的事物的类型,而不是int[4][5]. 此外,由于 astd::shared_ptr<>不知道它指向的内存位置有多少连续的东西,因此您还必须将维度传递给函数。


推荐阅读