【问题标题】:pretty-print C++ containers with indent by level逐级缩进的漂亮打印 C++ 容器
【发布时间】:2017-04-26 20:50:35
【问题描述】:

这是Kerrek SB 等上一个关于漂亮打印 STL 容器Pretty-print C++ STL containers 的问题的后续,Kerrek 等设法为此开发了一个非常优雅且完全通用的解决方案,以及它的续集Pretty-print std::tuple,其中std::tuple<Args...> 已处理。

我想知道是否可以在有关缩进的解决方案中加入?

例如,如果我有一个字符串向量的向量,我希望看到类似的内容:

{ // vector of vector of vector of string
   { // vector of vector of string
      { hello, world };// vector of string
      { The, quick, brown, fox, jumps, over, the, lazy, dog };
      ...
      { Now, is, the, time, for, all, good, men, to, come, to, the, aid, of, the, party}
   };
   { // vector of vector of string
      { hello, world };// vector of string
      { The, quick, brown, fox, jumps, over, the, lazy, dog };
      ...
      { Now, is, the, time, for, all, good, men, to, come, to, the, aid, of, the, party}
   };
   ...
   { // vector of vector of string
      { hello, world };// vector of string
      { The, quick, brown, fox, jumps, over, the, lazy, dog };
      ...
      { Now, is, the, time, for, all, good, men, to, come, to, the, aid, of, the, party}
   };
}

怎样才能做得很好?

【问题讨论】:

    标签: c++ c++11 templates pretty-print


    【解决方案1】:

    注意:这不是我解释的问题的 '真实' 答案,因为我怀疑 OP 想要一个通用解决方案,该解决方案对任意嵌套的容器使用适当的缩进.

    作为一种解决方法,您当然可以使用给定的解决方案并正确调整前缀、分隔符和后缀。

    Example:

    using namespace std::string_literals;
    
    using vs = std::vector<std::string>;
    using vvs = std::vector<std::vector<std::string>>;
    using vvvs = std::vector<std::vector<std::vector<std::string>>>;
    std::cout << pretty::decoration<vs>("       { ", ", ", " }");
    std::cout << pretty::decoration<vvs>("  {\n", ",\n", "\n    }");
    std::cout << pretty::decoration<vvvs>("{\n", ",\n", "\n}\n");
    
    std::vector<std::string> vs1 = { "hello"s, "world"s };
    std::vector<std::string> vs2 = { "The"s, "quick"s, "brown"s, "fox"s };
    std::vector<std::vector<std::string>> vvs1 = { vs1, vs1, vs2 };
    std::vector<std::vector<std::string>> vvs2 = { vs2, vs1, vs2 };
    std::vector<std::vector<std::vector<std::string>>> vvvs1 = { vvs1, vvs2 };
    
    std::cout << vvvs1;
    

    打印:

    {
        {
            { hello, world },
            { hello, world },
            { The, quick, brown, fox }
        },
        {
            { The, quick, brown, fox },
            { hello, world },
            { The, quick, brown, fox }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 2015-08-27
      • 1970-01-01
      • 2011-05-25
      相关资源
      最近更新 更多