是否有任何快捷方法来打印2D数组c ++

时间:2017-10-05 15:02:20

标签: c++ c++11 multidimensional-array

c ++中是否有输出2d数组的快捷方法(即除了for循环)? STL中是否有特殊功能可以输出它。

2 个答案:

答案 0 :(得分:0)

好吧,既然你提到了STL函数,你可以使用带有lambda函数的std :: for_each函数来打印2D数组:

#include <iostream>

using namespace std;
int main(int argc, char *argv[]) {
    int matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    auto elem_printer = [](int num) { std::cout << num << " "; };
    auto row_printer = [&elem_printer](int (&row)[3]) {
            std::for_each(std::begin(row),std::end(row),elem_printer);
            std::cout << std::endl;
    };  
    std::for_each(std::begin(matrix),std::end(matrix),row_printer);
}

然而,这与两个for循环完全相同,但更丑陋。

答案 1 :(得分:0)

我有这个流模板,它可以隐藏一些丑陋的东西,你可以从中获益,它可以处理多个维度。没有办法在没有在某处做循环的情况下离开,当然:

template <class Stream, size_t depth>
class Pretty
{
    Stream& s;
public:
    Pretty(Stream& s): s(s) {}
    template <size_t d1, typename T>
    Stream& operator <<( T const (&v)[d1])const
    {
        const char* sep = "{";
        for (auto& m : v)
        {
            s << sep << m;
            sep = ", ";
        }
        s << "}";
        return s;
    }
    template <size_t d1, typename T, size_t d2>
    std::ostream& operator <<(T const (&v)[d1][d2])const
    {
      enum {DENT = 4};
      std::string dent (DENT,' ');
      std::string indent(depth*DENT,' ');
      std::string sep = "{\n" + indent + dent;
      for (auto& m : v)
      {
          s << sep;   Pretty<Stream,depth+1>(s) << m;
          sep = ",\n" + indent + dent;
      }
      s << "\n" << indent << "}";
      return s;
    }
};

class PrettyNext
{};
Pretty<std::ostream,0> operator << (std::ostream& s, const PrettyNext&)
{
    return Pretty<std::ostream,0>(s);
}

用法:

int i [][3][2] = { { {1,2}, {3,4}, {5,6} },{{0}}};
std::cout << "This is a test:\n" << PrettyNext() << i << std::endl;

输出是:

This is a test:
{
    {
        {1, 2},
        {3, 4},
        {5, 6}
    },
    {
        {0, 0},
        {0, 0},
        {0, 0}
    }
}

我一直在努力让这个直接在std :: ostream上工作,但是与我无法解决的标准char *处理发生冲突。