今天用vs调试程序,想看看各个函数耗费时间,结果发现某些函数声明竟然长这样:
std::vector<std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,int>,std::allocator<std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,int> > >::emplace_back<char const (&)[5],int &>
而且我刚好又想看看这些个声明的结构,就想写个C++小程序,格式化输出这个声明,效果如下:
std::vector < std::pair < std::basic_string < char,std::char_traits<char>, std::allocator<char> >, int >, std::allocator < std::pair < std::basic_string < char,std::char_traits<char>, std::allocator<char> >, int > > >::emplace_back < char const (&)[5],int & >
这样就好理解多了,而且对于stl源码就够也很清晰了。
具体代码:
#include <fstream> #include <iostream> #include <memory> #include <string> #include <algorithm> using namespace std; const int tabCount = 4; void putTable(std::string & newContent,int level) { for (int i = 0; i < level; ++i) { for (int j = 0; j < tabCount; ++j) { newContent.push_back(‘ ‘); } } } void putLine(std::string & newContent) { newContent.push_back(‘\n‘); } void putChar(std::string & newContent, char c) { newContent.push_back(c); } int main(int argc, char **argv) { if (argc <= 1) { std::cout << "usage: formatStl filename" << endl; return 1; } std::cout << argv[1] << endl; fstream inputFile; inputFile.open(argv[1], fstream::in); if (inputFile.fail()) { std::cout << "open file error\n"; } inputFile.seekg(0, inputFile.end); int length = inputFile.tellg(); inputFile.seekg(0, inputFile.beg); ++length; char * buffer = new char[length]; if (!buffer) { std::cout << "new buffer failed!" << endl; } memset(buffer, 0, length); inputFile.read(buffer, length-1); std::string newContent; char *begen = buffer; char *end = buffer + length - 1; if (inputFile) { char * cur = buffer; int level = 0; while (*cur != 0) { if (*cur == ‘<‘) { auto it_r = find(cur, end, ‘>‘); auto it_l = find(cur + 1, end, ‘<‘); if (it_r < it_l) { while (cur <= it_r) { putChar(newContent, *cur); ++cur; } continue; }else{ putLine(newContent); putTable(newContent, level); putChar(newContent, *cur); putLine(newContent); ++level; putTable(newContent, level); } } else if (*cur == ‘>‘) { --level; putLine(newContent); putTable(newContent, level); putChar(newContent, *cur); } else if (*cur == ‘,‘) { putChar(newContent, *cur); if (*(cur - 1) == ‘>‘) { putLine(newContent); putTable(newContent, level); } } else { putChar(newContent, *cur); } ++cur; } std::cout << newContent << endl; } else { std::cout << "error: only " << inputFile.gcount() << " could be read"; } delete[] buffer; std::cout << "exit!" << endl; return 0; }
后来发现,这样也还是很麻烦啊,每次还要保存到一个文件,再去运行这个程序,不是很扯淡么?
正好最近在用sublime,直接做个插件行不行,网上搜了下教程,发现好像不是很复杂,用python开发,不如试一下,效果如下:
格式化之前:
格式化之后:
凑合能用吧
原文:http://www.cnblogs.com/SillyFlame/p/5154266.html