「模板」代码风格指北

别 tm define int long long 了

介绍一下本人在算法竞赛中常用的代码规范。

Fork from:

  • jiangly;
  • menci;
  • Google;
  • 还有我自古以来的习惯。

第一部分

  • 使用四个半角空格缩进,不使用制表符;
  • 大括号不换行;
  • 符号之间一般会有空格;
  • 同一作用域下的不同意义代码块用空行隔开;
  • 指针、左值引用和右值引用类型中的 *& 不应放在变量名之前;
    • 即:使用 auto& x 而不是 auto &x

第二部分

  • 变量命名一般使用小写字母;
  • 用下划线 _ 分割单词;

第三部分

  • 不使用 using namespace std;
  • 不使用 #define int long long
  • 一般不使用全局变量,尤其是全局数组;
  • 使用左闭右开区间;
  • 使用 0-index

第四部分

  • 对于 C++ 版本在 20 以上的,使用 std::ranges
  • 能使用 lambda 函数的就使用 lambda 函数;
  • 使用 std::cinstd::cout 而不是 printf 或者 scanf
  • 使用 emplace 或者 emplace_back,需要使用 {} 初始化的除外;
  • 如果对顺序没有要求,使用 unordered_mapunordered_set
  • 如果大小确定且较小,使用随机存取容器;

模板

基本模板

update on April 8.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>

namespace rgs = std::ranges;
namespace vws = std::views; 

using i32 = int32_t; using u32 = uint32_t;
using i64 = int64_t; using u64 = uint64_t;
using i128 = __int128; using u128 = unsigned __int128;

constexpr auto endl = "\n", yes = "YES", no = "NO";

auto solve() {

}

auto main() -> i32 {
    std::cin.tie(nullptr)->sync_with_stdio(false);
    i32 t = 1;
    std::cin >> t;
    while (t--) {
        solve();
    } 
    return 0;
}

常用操作

二分查找

1
2
3
4
5
auto lo = 0, hi = 100;
auto check = [](auto x) {
    return true;
};
auto res = *rgs::partition_point(vws::iota(lo, hi), check);

读入

1
2
3
4
5
int n;
std::cin >> n;
std::vector<int> a(n);
for (auto& x : a)
    std::cin >> x;

输出

1
2
3
for (auto i : rep(a.size())) {
    std::cout << a[i] << " \n"[i == a.size() - 1];
}

存图

1
2
3
4
5
6
7
8
auto adj = std::vector(n, std::vector<int>{});
for (auto i : rep(n)) {
    int u, v;
    std::cin >> u >> v;
    u --, v --;
    adj[u].emplace_back(v);
	adj[v].emplace_back(u);
}

递归

1
2
3
4
5
6
7
auto dfs = [&](this auto&& self, int x, int p) -> void {
    for (auto y : adj[x]) {
	    if (y == p)
	        continue;
		self(y, x);
    }
}

以上代码对于 C++23 使用;对于更低的版本,推荐使用如下写法:

1
2
3
4
5
6
7
function<void(int,int)> dfs = [&](int x, int p) {
   for (auto y : adj[x]) {
       if (y == p)
	       continue;
	    dfs(y, x);
   }
}

随机

1
auto rand_int = std::mt19937(std::chrono::steady_clock::now().time_since_epoch().count());
Licensed under CC BY-NC-SA 4.0
赣ICP备2024042422号
使用 Hugo 构建
主题 StackJimmy 设计