c++ - 按级别缩进的 pretty-print C++ 容器

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

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

我想知道是否可以包含有关缩进的解决方案?

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

{ // 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}
   };
}

怎样才能做得好?

最佳答案

注意:这不是我解释的问题的'真实'答案,因为我怀疑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 }
    }
}

关于c++ - 按级别缩进的 pretty-print C++ 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41093221/

相关文章:

C++11:如何用 nullptr 初始化某个类的指针数组?

c++ - 为什么将 T 从外部模板作为默认参数传递给 std::function 会导致编译错误?

multithreading - 访问boost::asio::ip::tcp::socket时,C++ 11线程崩溃

c++ - 将 void* 转换为具有多重继承的类

c++ - 在 Eclipse CDT 中输入 EOF 字符(Ctrl+D)

c++ - 类(class)尚未宣布但已包括在内?

c++ - sqlite3_prepare_v2 返回错误 1 ​​代码

c++ - 使用 Directx10 渲染

c++ - 我如何对两个参数使用偏特化

c++ - 如何检测作为参数传递的函数的参数类型?