C++

容器类

string

static constexpr size_type npos = size_type(-1); // npos = -1

// 从 pos 开始查找某个子串,找不到返回 npos (即-1),否则返回第一次出现的下标
constexpr size_type find(const basic_string& str, size_type pos = 0) const noexcept;

// 返回子串 [pos, pos + count - 1] 若 count 省略,则返回 [pos, s.size() - 1] 的子串
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) &&;

vector

vector<T> a, b;
...
a = b; // 将 a 中内容复制到 b

set, multiset

multiset<int> ms;
int x = *(--ms.end()); // 查询集合中的最大值

算法 <algorithm>

随机化

mt19937 rnd(time(NULL)); // 用当前Epoch到现在的秒数定义一个随机种子
unsigned int a = rnd(); // 返回一个 32 位无符号随机整数

mt19937_64 rndll(time(NULL)); // 定义一个 64 位的随机种子
ull a = rndll(); // 返回一个 64 位无符号随机整数

// 将 [first, last) 随机打乱,随机种子是 g
template< class RandomIt, class URBG >
void shuffle( RandomIt first, RandomIt last, URBG&& g );

// 生成随机排列
int a[N+5];
for (int i = 1; i <= n; i++) a[i] = i;
shuffle(a + 1, a + n + 1, rnd);

二分

// 使用自定义比较函数:返回第一个 comp(*it, value) 为 false 的位置,没找到返回 last
constexpr ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp );

其他语法相关内容

引用所占空间与指针相同

inline

玄学编译优化

通常适用于比较简单的函数

  1. 无递归
  2. 并查集 get(建议直接写非递归形式)
  3. exgcd

下划线函数

__builtin_popcount(x); // 返回 1 的个数
__builtin_ctz(x); // 返回末尾 0 的个数
__builtin_clz(x); // 返回前导 0 的个数
__builtin_sqrt(x); // 开平方向下取整
// 以上函数参数均为 32  位无符号整数,若要使用 64 位,在后面加上 'll'

// 注意:__builtin_ctz 和 __builtin_clz 在参数为 0 时行为是未定义的!!!

#define popcnt(x) __builtin_popcount(x)
#define ctz(x) ((x) ? __builtin_ctz(x) : 0)
#define clz(z) ((x) ? __builtin_clz(x) : 32)

#define popcntll(x) __builtin_popcountll(x)
#define ctzll(x) ((x) ? __builtin_ctzll(x) : 0)
#define clzll(z) ((x) ? __builtin_clzll(x) : 64)

__lg(x) // 返回下取整 log2 x,x 不能为 0

输入输出

bool a[N+5];
for (int i = 1; i <= n; i++)
	scanf("%1d", &a[i]); // 不要使用,慢到爆炸

char s[N+5];
scanf("%s", s + 1);
for (int i = 1; i <= n; i++) a[i] = s[i] - '0';

posted @ 2025-10-27 19:26  zhm0725  阅读(6)  评论(0)    收藏  举报