理念
优先级从高到低依次为:可读、简洁。
零散
禁用 using namespace std;。
禁止 bool 和 int 混用。bool 变量赋值 必须用 true 或 false。
后置 自增自减,禁止 前置。如可简化写法使用前置(如 num++;e[num] = {to, head[from]} 就应该写成 e[++num] = {to, head[from]})。
对于常用函数,与常用数据结构,尽量 使用 STL。
缩进
全局采用 3 tab 缩进(使用 tab,占用三字节)。
特殊情况:
#ifdef与#ifndef内 不缩进,即:C++ int main() { #ifdef AAA /* 不缩进 */ #endif }- 括号中内容过多,从左括号开始写。逗号,分号,与或符号换行写,用 CLion 的自动对齐以对齐。
空格
#include后接空格;所有尖括号(<、>)之间都禁止加空格;- 运算符:双目、三目运算符 两端空格,单目运算符 不加空格;
- 逗号后统一 后置空格;
- 其他空格基本按照 CLion 标准。
空行
通常对于两个部分,意义不同 则空行。不出现 连续超过两行空行。
变量申明后 紧接 初始化(static 除外)。#include、#define、namespace 中间空行。
如:
#include <iostream>
#include <iomanip>
#include <cmath>
constexpr int N = 1e5 + 5;
namespace DataStruct{
/* Code Something. */
}通常空行分区为:定义、输入、预处理、核心、答案。
语句
if-else :
if (/* Condition 1 */) {
/* Do Something. */
} else if (/* Condition 2 */) {
/* Do Something. */
} else {
/* Do Something. */
}for :
for (int i = 1; i <= n; i++) {
/* Do Something. */
}
for (auto it : set) {
/* Do Something. */
}while :
while () {
/* Do Something. */
}
do {
/* Do Something. */
}switch :
switch (/* option */) {
case 1:
/* Do Something. */
break;
case 2:
/* Do Something. */
break;
case 3:
/* Do Something. */
break;
default:
/* Do Something. */
break;
}注 : 不必要时不用 default。
goto :
int main() {
for (int i = 1; i <= n; i++) {
if (a[i] < 0) {
goto _w;
}
}
_w:write(a[n]);
}标签正常缩进,下划线加名字。与正常变量命名方式类似。
命名
常量尽量使用 constexpr,全部大写。当题目对数据量有要求时,常用它对应的大写字母表示最大量,并用小写字母表示它本身。如 n 与 N;m 与 M。
变量名使用该变量的英文简写,如 count -> cnt、delta -> dt 等。
函数按照常规叫法命名。如 DFS 写作 void dfs(),Tarjan 写作 void tarjan();如果是自定义函数,则按照下划线命名法。如 int get_num()。如果函数名大于等于 10 个字符(包含下划线)时,则取其每个单词的首字母作为函数名。如 int char_to_num() -> int ctn()。
如果同类函数有多个,则在函数名后面加序号辨别。如 void dfs1(),void dfs2()。
括号
小括号
类型强制转换一定要带括号,格式:
((类型名)变量名)大括号
无论 for、while、if-else 语句中有一个语句还是多个语句,这些语句都会被一对大括号包裹。
e.g.:
if (!flag) {
continue;
}