【问题标题】:Smart pointer 2D array as a parameter智能指针二维数组作为参数
【发布时间】:2019-03-17 04:47:54
【问题描述】:

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

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++ function c++11 multidimensional-array smart-pointers


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 2016-03-19
    • 2013-03-07
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2015-01-12
    • 2012-09-06
    • 1970-01-01
    相关资源
    最近更新 更多