使用模板打印嵌套数组

时间:2015-06-30 07:22:01

标签: c++ arrays templates multidimensional-array pretty-print

我有以下代码来打印数组 - :

// Print an array
// Does not work on nested arrays !
template<typename T1, size_t arrSize>
void printArray( T1 const( & arr )[arrSize], std::ostream& out = std::cout )
{
    out << "[";
    if ( arrSize )
    {
        for ( size_t it = 0; it != arrSize - 1; ++it )
        {
            out << arr[it] << ", ";
        }
        // Print the last element separately to avoid the extra characters following it.
        out << arr[arrSize - 1];
    }
    out << "]";
}

int arr[5][5];

int main()
{
    printArray( arr[0] );
    printArray( arr );
}

输出 - :

  

[0,0,0,0,0]
  [0x489040,0x489054,0x489068,0x48907c,0x489090]

虽然在单维数组的情况下它可以正常工作,但在多维数组的情况下,该函数会打印数组的单个地址而不是它们的内容。

有没有办法使用单个函数调用打印通用多维数组?

我正在使用带有-std=c++14标志的GCC 4.9.2。

1 个答案:

答案 0 :(得分:3)

你必须有一个数组函数,一个用于单个元素:

// Print a single element (use in array version)
template<typename T>
void printArray(T const &e, std::ostream& out = std::cout )
{
    out << e;
}

// Print an (nested) array
template<typename T1, size_t arrSize>
void printArray(T1 const(& arr)[arrSize], std::ostream& out = std::cout )
{
    out << "[";
    const char* sep = "";
    for (const auto& e : arr)
    {
        out << sep;
        printArray(e, out);
        sep = ", ";
    }
    out << "]";
}

Live Demo

相关问题