代码格式化的意义
很多人编写程序时不注意程序的版式结构,这样做虽然不会影响程序的功能,但是程序的可读性会大大降低。
C++
语言的格式很自由,这意味着换行、空格、空行和制表符等空白在程序运行时都会被忽略,程序员可以使用空白让代码按照特定的风格缩进或分开,使程序更加清晰易懂。
个人认为,在OI考场上,一个优秀的码风可以有些提高你的调试效率。
假设我们写的是文章而不是程序,那么你一定觉得诸如文章应该分为若干个自然段、每段开头空两格之类的规则是理所当然的。如果段落的开头不空两格,或者干脆把整个文章写成单独的一段,仔细想来似乎也不会影响文章实质内容的表达。既然如此,我们为什么还要在形式上下功夫呢?设想一下,如果你手中的这本书既无章节也无目录,正文中的不同内容都使用同样的字体字号印刷,几百页纸从头至尾洋洋洒洒如念经般地“一气呵成”,你还有耐心看下去吗?
这是一个人人都能理解的道理,可是当文章变成程序的时候,就不是每个人都能想得通的了。不仅仅是初学者,甚至一些熟练的开发人员,也会写出凌乱不堪的代码。许多人一定有过这样的经历:一年半载之后,自己原来写的程序就完全看不懂了。如果这段程序只是为了交作业,或者临时一用,那还可以不去追究,但如果这是一个商业软件,现在需要根据客户的要求进行修改的话,工作量可就大了——你不得不先花时间把你原来的思路看懂。
肯定会有人反驳:代码是给机器运行的,又不是给人看的,写那么好看有什么用?
他的话只对了前半句:代码确实是给机器运行的,可是机器总共才需要看它几分钟?你花一个月编写的程序,机器顶多两三分钟就编译好了——在这两三分钟之前,这代码不都是你在看吗?开发软件编写代码不是一朝一夕的事情,更多的情况下,一个软件的开发要经历很长的时间,并且常常由多人合作完成。一个庞大的软件项目,可能会动用上千名程序员工作数年!如果把代码写得连自己都看不明白,怎么与别人交流?同一个开发团队内,一定要保持良好且一致的代码风格,才能最大化地提高开发效率。
代码格式化演示
感谢@xlj2596提供的洛谷P3371代码,评测ID:R16227912。
格式化前代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| #include<cstdio> #include<cstring> #include<algorithm> const int maxm=10005; const int maxn=500005; using namespace std; bool vis[maxm]; int N,M,S,F,G,W,_start,_end,_size,Q[4000005],f[maxm],to[maxn<<1],val[maxn<<1],nxt[maxn<<1],las[maxn<<1]; inline void addedge(int x,int y,int z){_size++;to[_size]=y;val[_size]=z;nxt[_size]=las[x];las[x]=_size;} inline void spfa(){ _end=1;_start=1;f[S]=0;Q[1]=S; memset(f,63,sizeof(f)); while(_start<=_end){ int x=Q[_start++]; vis[x]=false; for(int i=las[x];i;i=nxt[i]){ if(f[x]+val[i]<f[to[i]]){ f[to[i]]=f[x]+val[i]; if(!vis[to[i]]){ vis[to[i]]=true; Q[++_end]=to[i]; } } } } } int main(){ scanf("%d%d%d",&N,&M,&S); for(int i=1;i<=M;i++){scanf("%d%d%d",&F,&G,&W);addedge(F,G,W);} spfa(); for(int i=1;i<=N;i++){ printf("%d%c",f[i]>1e9?2147483647:f[i],i==N?'\n':' '); } return 0; }
|
格式化后代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| #include <algorithm> #include <cstdio> #include <cstring> const int maxm = 10005; const int maxn = 500005; using namespace std; bool vis[ maxm ]; int N, M, S, F, G, W, _start, _end, _size, Q[ 4000005 ], f[ maxm ], to[ maxn << 1 ], val[ maxn << 1 ], nxt[ maxn << 1 ], las[ maxn << 1 ]; inline void addedge( int x, int y, int z ) { _size++; to[ _size ] = y; val[ _size ] = z; nxt[ _size ] = las[ x ]; las[ x ] = _size; } inline void spfa() { _end = 1; _start = 1; f[ S ] = 0; Q[ 1 ] = S; memset( f, 63, sizeof( f ) ); while ( _start <= _end ) { int x = Q[ _start++ ]; vis[ x ] = false; for ( int i = las[ x ]; i; i = nxt[ i ] ) { if ( f[ x ] + val[ i ] < f[ to[ i ] ] ) { f[ to[ i ] ] = f[ x ] + val[ i ]; if ( !vis[ to[ i ] ] ) { vis[ to[ i ] ] = true; Q[ ++_end ] = to[ i ]; } } } } } int main() { scanf( "%d%d%d", &N, &M, &S ); for ( int i = 1; i <= M; i++ ) { scanf( "%d%d%d", &F, &G, &W ); addedge( F, G, W ); } spfa(); for ( int i = 1; i <= N; i++ ) { printf( "%d%c", f[ i ] > 1e9 ? 2147483647 : f[ i ], i == N ? '\n' : ' ' ); } return 0; }
|
C++
对于C++
,普遍使用clang-format
来格式化代码,当然,你也可以选择Visual Studio
来格式化代码。这里,我们不介绍Visual Studio
的安装,请自行 百度。
Windows
玩家
建议直接下载clang-format
程序,百度即可下载。
你可以使用命令行来调用程序,详见百度。
下载Clang
提供完整体验
clang-format程序作为 Clang 的一部分,你可以选择下载整个包以获得完整体验。
Clang是一个C语言、C++、Objective-C语言的轻量级编译器。源代码发布于BSD协议下。Clang将支持其普通lambda表达式、返回类型的简化处理以及更好的处理constexpr关键字。截至本文章发表时,Clang的最新版是11.0.1。
VSCode玩家
在插件页面安装cpptools插件,你就可以对选中代码块使用Ctrl+K,Ctrl+F
来格式化代码。
Ubuntu
玩家
1
| sudo apt install clang-format
|
CentOS
玩家(未经实验)
1
| sudo yum install clang-format
|
安装完成后,你就可以开始下一步操作了。
配置你的代码风
本实验基于Windows 10 x64 1089 专业版 & VSCode 1.31.0。
基于上述方法安装后,你可以打开一个文件夹,如下图所示。

新建一个文件,叫做.clang-format
或者_clang-format
。
在Linux文件系统中,以一个英文句点开始的文件名的文件具有隐藏属性,所以你可能需要调整设置以显示它 。
Windows玩家可能发现自己使用资源管理器无法新建以这个名字命名的文件,请使用命令行或Vscode。
然后打开这个文件,就像这样。
输入你的配置文件,保存并关闭。
这样你就可以使用代码格式化了。选中你要格式化的部分并按下Ctrl+K,Ctrl+F
就可以格式化,或者按下Shift+Alt+F
全文格式化。
此处的Ctrl+K,Ctrl+F是指先按Ctrl+K,再按Ctrl+F。你可以在文件-首选项-键盘快捷方式里修改快捷键。
配置文件的书写
模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
| ---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true BreakBeforeBraces: Custom
BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false BeforeCatch: false BeforeElse: true IndentBraces: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 - Regex: '^(<|"(gtest|isl|json)/)' Priority: 3 - Regex: '.*' Priority: 1
IndentCaseLabels: false
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 80
PenaltyReturnTypeOnItsOwnLine: 80
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: true
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: true
SpacesInParentheses: true
SpacesInSquareBrackets: true
Standard: Cpp11
TabWidth: 4
UseTab: Never
|
语法
配置文件使用YAML
语法,大抵概括如下:
- 所有的注释以
#
开头。
- 所有的值以
Key: Value
形式出现,每行一个,冒号是英文冒号,冒号后面空一格或者一个Tab 。
参数解释
这里只解释一些容易出现错误或者混淆的参数,其余参数,请参见 Clang格式样式选项 或阅读附图上的谷歌翻译后的文档。如果阅读后还有异议,请在下方评论,博主会酌情回答和解释。
易出现错误或者混淆的参数
Language:字符串,取值范围。该配置文件针对的语言。请填写Cpp
,不是cpp
,cpp11
,C++
,kkkAKIOI
等。
- None:不要使用。
- Cpp:C,C++。
- Java:Java。
- JavaScript:JavaScript。
- ObjC:Objective-C,Objective-C++。
- Proto:协议缓冲区。
- TableGen:TableGen。
- TextProto:文本格式的协议缓冲消息。
BasedOnStyle:字符串,取值范围。基于的语言。点击链接可以查看内容和效果。当你没有配置值的时候,参考你所选择的标准。
AccessModifierOffset:整型。public、private等的偏移,如下图。一般用不到。
AlignAfterOpenBracket:BracketAlignmentStyle,取值范围。开括号(开圆括号、开尖括号、开方括号)后的对齐方式。
1 2
| someLongFunction(argument1, argument2);
|
1 2
| someLongFunction(argument1, argument2);
|
- AlwaysBreak 如果参数不适合单行,则在开括号后断开
e.g.
1 2
| someLongFunction( argument1, argument2);
|
- AlignConsecutiveAssignments:布尔值。对齐连续分配。如果取值为真,对齐连续行的赋值运算符。
e.g.
1 2 3
| int kkk = 666; int cz = 888; int c = 999;
|
AlignConsecutiveDeclarations:布尔值。如果取值为真,对齐连续行的声明名称。
e.g.
1 2 3
| int aaaa = 12; float b = 23; std::string ccc = 23;
|