c++ - 如何在c++中打印n维数组

标签 c++ arrays function

我想编写一个可以打印不同数组的函数。例如:

#include<iostream>
using namespace std;
int main(){
    int a[10];
    int b[3][2];
    for(int i = 0; i < 10; i++){
        a[i] = i;
    }
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 2; j++){
            b[i][j] = i * 2 + j;
        }
    }
    print_arr(a, /*some input*/);
// output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    print_arr(b, /*some input*/);
// output: 
// 0, 1
// 2, 3
// 4, 5
   return 0;
}

有人可以帮助我或说这是不可能的吗? 也许这个问题已经有了答案。在这种情况下,请您分享该问题的链接

最佳答案

您可以创建一个函数模板来递归地解开数组。

示例:

#include <iostream>
#include <type_traits>

// only enable the function for arrays
template<class T, std::enable_if_t<std::is_array_v<T>, int> = 0>
void print_arr(const T& x) {
    for(auto& in : x) {
        if constexpr (std::rank_v<T> > 1) // more dimensions to go
            print_arr(in);                // call to unwrap next dimension
        else
            std::cout << in << ' ';       // last dimension, print the value
            
    }
    std::cout << '\n';
}

Demo

由于名称 print_arr 表明您不需要 SFINAE您还可以将模板的 enable_if_t 部分替换为函数内的 static_assert :

template<class T>
void print_arr(const T& x) {
    static_assert(std::is_array_v<T>);
    // ...

您可以添加一个 std::ostream& 参数来使其流式传输到任何流,而不是直接流式传输到std::cout

template<class T>
void print_arr(std::ostream& os, const T& x) {
    static_assert(std::is_array_v<T>);
    for(auto& in : x) {
        if constexpr (std::rank_v<T> > 1)
            print_arr(os, in);
        else
            os << in << ' ';
            
    }
    os << '\n';
}

// ...

    print_arr(std::cout, a);
    print_arr(std::cout, b);

或者您可以让它返回完整输出的 std::string ,这样您以后就可以用它做您想做的事情。

示例:

#include <sstream>

template<class T>
std::string print_arr(const T& x) {
    static_assert(std::is_array_v<T>);
    std::ostringstream os;

    for(auto& in : x) {
        if constexpr (std::rank_v<T> > 1)
            os << print_arr(in);
        else
            os << in << ' ';
            
    }
    os << '\n';
    return os.str();
}

// ...

    std::cout << print_arr(a);
    std::cout << print_arr(b);

关于c++ - 如何在c++中打印n维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67651040/

相关文章:

javascript - javascript中的高阶函数是什么意思?

c++ - 在 OpenGL 中渲染 QWidget

c++ - 为什么从 bind 返回的对象会忽略额外的参数?

Javascript:将数据分配给多维数组

c++ - 在 C++ 中对自定义对象的 vector 进行操作

jquery - 为一种功能提供更多效果。 jQuery

c++ - 围绕当前位置旋转矩阵的快速方法

c++ - 使用 GAlib 模板实例化的 Cygwin gcc 编译器问题

c++ - C++ 中的数组和覆盖 - 我可以重用同一个对象吗?

javascript - 如何在javascript中从数组制作二叉树?