【问题标题】:Can a multiple dimension array be passed as a single pointer parameter?可以将多维数组作为单个指针参数传递吗?
【发布时间】:2017-05-12 13:59:06
【问题描述】:
int f(char* x)
{
    //something
}
int main(int argc,char** argv)
{
    char arr[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
    f(arr);
    return 0;
}

我无法预料程序员会传递多少维数组。所以我想让这个函数得到一个多维数组作为单个参数。有可能吗?

【问题讨论】:

  • 您需要一些有关尺寸的信息。你可以通过它,但除非你知道那里有什么,否则它不会有用。也许您应该考虑创建一个类来包装您的数据并包含程序员必须提供的元信息。

标签: arrays parameter-passing c++14


【解决方案1】:

您可以通过使用模板来推断数组的大小来实现这一点:

template<const std::size_t rows, const std::size_t cols>
int f(char (&arr)[rows][cols])

您的完整代码如下所示:

#include <cstdio>
template<const std::size_t rows, const std::size_t cols>
int f(char (&arr)[rows][cols])
{
    //something
}
int main(int argc,char** argv)
{
    char arr[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
    f(arr);
    return 0;
}

这也可能有帮助:Passing a 2D array to a C++ function

【讨论】:

    【解决方案2】:

    如果你不知道数组的维度个数,你就必须发挥创造力:

    template <class T, std::enable_if_t<std::is_array<T>::value, int> = 0>
    void f(T &arr) {
        constexpr auto dimensions = std::rank<T>::value;
    
        std::cout << "Received array with " << dimensions << " dimensions!";
    }
    

    您可以使用std::rankstd::extent 检索有关阵列几何的信息。

    See it live on Coliru!

    【讨论】:

    • 谢谢。我很高兴知道有什么输出数组的维数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多