C/C++ 标准库 API 速查 / C/C++ Standard Library Quick Reference
中英双语速查手册,涵盖 C 标准库与 C++ 标准库核心 API。
Bilingual quick reference covering C and C++ standard library core APIs.
参考:cppreference.com / cppreference.cn / c.biancheng.net
目录 / Table of Contents
C 标准库 (C Standard Library / C 标准库)
<string.h> / 字符串操作 / String Operations
memcpy / 内存拷贝 / Memory Copy
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
void *memcpy(void *dest, const void *src, size_t n); |
| 说明 / Description |
从 src 复制 n 字节到 dest。源和目标内存区域不可重叠。Copies n bytes from src to dest. Regions must not overlap. |
| 参数 / Parameters |
dest - 目标指针 / destination pointer; src - 源指针 / source pointer; n - 字节数 / byte count |
| 返回值 / Return |
dest 指针 |
| 复杂度 / Complexity |
O(n) |
| 安全 / Safety |
⚠️ 内存重叠时行为未定义,重叠区域用 memmove |
char src[] = "hello";
char dst[6];
memcpy(dst, src, 6); // dst == "hello"
memmove / 安全内存拷贝 / Safe Memory Copy
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
void *memmove(void *dest, const void *src, size_t n); |
| 说明 / Description |
从 src 复制 n 字节到 dest,源和目标可以重叠。Copies n bytes; handles overlapping regions. |
| 参数 / Parameters |
同 memcpy |
| 返回值 / Return |
dest |
| 复杂度 / Complexity |
O(n) |
char buf[] = "abcdef";
memmove(buf + 2, buf, 4); // buf == "ababcd"
memset / 内存填充 / Memory Set
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
void *memset(void *dest, int c, size_t n); |
| 说明 / Description |
将 dest 的前 n 字节设为 c(转为 unsigned char)。Sets first n bytes of dest to c. |
| 参数 / Parameters |
dest - 目标; c - 填充值; n - 字节数 |
| 返回值 / Return |
dest |
| 复杂度 / Complexity |
O(n) |
int arr[10];
memset(arr, 0, sizeof(arr)); // 全部置零 / zero-fill
memcmp / 内存比较 / Memory Compare
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
int memcmp(const void *s1, const void *s2, size_t n); |
| 说明 / Description |
比较前 n 字节。Compares first n bytes. 返回 <0/0/>0 表示 s1 小于/等于/大于 s2。 |
| 返回值 / Return |
负数/0/正数 |
| 复杂度 / Complexity |
O(n) |
memchr / 内存搜索 / Memory Character Search
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
void *memchr(const void *s, int c, size_t n); |
| 说明 / Description |
在前 n 字节中查找 c。Searches for c in first n bytes. |
| 返回值 / Return |
找到的指针,未找到返回 NULL |
strcpy / 字符串拷贝 / String Copy
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
char *strcpy(char *dest, const char *src); |
| 说明 / Description |
将 src(含 \0)复制到 dest。Copies src including null terminator to dest. |
| 安全 / Safety |
⚠️ 缓冲区溢出风险,推荐 strncpy 或 snprintf |
char dst[20];
strcpy(dst, "hello");
strncpy / 有限字符串拷贝 / Bounded String Copy
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
char *strncpy(char *dest, const char *src, size_t n); |
| 说明 / Description |
最多复制 n 字节。如果 strlen(src) < n,剩余字节填充 \0。Copies up to n bytes. |
| 安全 / Safety |
⚠️ 不保证以 \0 结尾(当 strlen(src) >= n 时) |
strlcpy / 安全字符串拷贝 / Safe String Copy (BSD)
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> (BSD / macOS) |
| 原型 / Prototype |
size_t strlcpy(char *dest, const char *src, size_t size); |
| 说明 / Description |
最多复制 size-1 字节,始终保证 \0 结尾。返回 strlen(src)。Guaranteed null-termination. |
| 安全 / Safety |
✅ 安全,返回完整源串长度便于截断检测 |
char buf[8];
strlcpy(buf, "hello world", sizeof(buf)); // buf == "hello w", 返回 11
strcat / 字符串连接 / String Concatenation
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
char *strcat(char *dest, const char *src); |
| 说明 / Description |
将 src 追加到 dest 末尾。Appends src to dest. |
| 安全 / Safety |
⚠️ 缓冲区溢出风险,推荐 strncat 或 snprintf |
strncat / 有限字符串连接 / Bounded String Concatenation
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
char *strncat(char *dest, const char *src, size_t n); |
| 说明 / Description |
最多追加 n 字节,始终以 \0 结尾。Appends up to n bytes, always null-terminated. |
strlcat / 安全字符串连接 / Safe String Concatenation (BSD)
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> (BSD / macOS) |
| 原型 / Prototype |
size_t strlcat(char *dest, const char *src, size_t size); |
| 说明 / Description |
安全连接,返回尝试创建的字符串总长度。Safe concatenation, returns total intended length. |
strlen / 字符串长度 / String Length
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
size_t strlen(const char *s); |
| 说明 / Description |
返回字符串长度(不含 \0)。Returns length excluding null terminator. |
| 返回值 / Return |
字符串长度 / string length |
| 复杂度 / Complexity |
O(n) |
strcmp / 字符串比较 / String Compare
| 项目 / Item |
内容 |
| 头文件 / Header |
<string.h> / <cstring> |
| 原型 / Prototype |
int strcmp(const char *s1, const char *s2); |
| 说明 / Description |
按字典序比较。返回 <0/0/>0。Lexicographic comparison. |
| 复杂度 / Complexity |
O(n) |
strncmp / 有限字符串比较 / Bounded String Compare
| 项目 / Item |
内容 |
| 原型 / Prototype |
int strncmp(const char *s1, const char *s2, size_t n); |
| 说明 / Description |
最多比较前 n 个字符。Compares up to n characters. |
strchr / 字符查找(正向)/ Find Character (Forward)
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *strchr(const char *s, int c); |
| 说明 / Description |
查找 c 第一次出现的位置。Finds first occurrence of c. |
strrchr / 字符查找(反向)/ Find Character (Reverse)
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *strrchr(const char *s, int c); |
| 说明 / Description |
查找 c 最后一次出现的位置。Finds last occurrence of c. |
strstr / 子串查找 / Substring Search
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *strstr(const char *haystack, const char *needle); |
| 说明 / Description |
查找 needle 在 haystack 中首次出现的位置。Finds first occurrence of substring. |
| 返回值 / Return |
匹配位置的指针,未找到返回 NULL |
| 复杂度 / Complexity |
O(n*m) 最坏情况 |
const char *s = "hello world";
char *p = strstr(s, "world"); // p 指向 "world"
strtok / 字符串分割 / String Tokenize
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *strtok(char *str, const char *delim); |
| 说明 / Description |
按 delim 分割字符串。首次调用传字符串,后续传 NULL。Tokenizes string by delimiters. |
| 安全 / Safety |
⚠️ 修改原字符串,非线程安全。多线程用 strtok_r |
char s[] = "one,two,three";
char *tok = strtok(s, ",");
while (tok) {
printf("%s\n", tok);
tok = strtok(NULL, ",");
}
strerror / 错误码转字符串 / Error Code to String
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *strerror(int errnum); |
| 说明 / Description |
返回描述错误码的字符串。Returns string describing error code. |
| 安全 / Safety |
⚠️ 非线程安全,多线程用 strerror_r |
<stdlib.h> / 通用工具 / General Utilities
malloc / 内存分配 / Memory Allocation
| 项目 / Item |
内容 |
| 头文件 / Header |
<stdlib.h> / <cstdlib> |
| 原型 / Prototype |
void *malloc(size_t size); |
| 说明 / Description |
分配 size 字节未初始化内存。Allocates size bytes of uninitialized memory. |
| 返回值 / Return |
指针或 NULL(失败时) |
| 复杂度 / Complexity |
O(1) ~ O(n) 取决于实现 |
| 安全 / Safety |
⚠️ 分配失败返回 NULL,需检查;不初始化内存 |
int *p = malloc(100 * sizeof(int));
if (!p) { /* 处理错误 */ }
free(p); p = NULL;
calloc / 分配并清零 / Allocate and Zero
| 项目 / Item |
内容 |
| 原型 / Prototype |
void *calloc(size_t nmemb, size_t size); |
| 说明 / Description |
分配 nmemb * size 字节并初始化为零。Allocates and zero-initializes. |
int *arr = calloc(100, sizeof(int)); // 100 个 int,全零
realloc / 重新分配 / Reallocate
| 项目 / Item |
内容 |
| 原型 / Prototype |
void *realloc(void *ptr, size_t size); |
| 说明 / Description |
调整已分配内存块大小。保留原数据(min(old, new) 字节)。Resizes memory block, preserves data. |
| 安全 / Safety |
⚠️ 失败返回 NULL 但原指针仍有效,应使用临时变量接收 |
int *tmp = realloc(p, 200 * sizeof(int));
if (tmp) p = tmp;
else { /* 保留 p,处理错误 */ }
free / 释放内存 / Free Memory
| 项目 / Item |
内容 |
| 原型 / Prototype |
void free(void *ptr); |
| 说明 / Description |
释放 malloc/calloc/realloc 分配的内存。Frees allocated memory. |
| 安全 / Safety |
⚠️ 不可释放栈内存、已释放内存(double free)、NULL 可安全释放 |
atoi / 字符串转整数 / String to Integer
| 项目 / Item |
内容 |
| 原型 / Prototype |
int atoi(const char *str); |
| 说明 / Description |
将字符串转为 int。转换失败行为未定义。Converts string to int. |
| 安全 / Safety |
⚠️ 无错误检测,推荐 strtol |
strtol / 字符串转长整数 / String to Long
| 项目 / Item |
内容 |
| 原型 / Prototype |
long strtol(const char *str, char **endptr, int base); |
| 说明 / Description |
将字符串转为 long,支持指定进制和错误检测。Converts with base and error detection. |
| 参数 / Parameters |
str - 字符串; endptr - 存储第一个未转换字符的位置(可 NULL); base - 进制(0=自动检测, 8/10/16) |
| 返回值 / Return |
转换结果,溢出时为 LONG_MAX/MIN 并设 errno |
char *end;
long val = strtol("123abc", &end, 10); // val=123, end 指向 "abc"
strtoul / 字符串转无符号长整数 / String to Unsigned Long
| 项目 / Item |
内容 |
| 原型 / Prototype |
unsigned long strtoul(const char *str, char **endptr, int base); |
strtod / 字符串转双精度浮点 / String to Double
| 项目 / Item |
内容 |
| 原型 / Prototype |
double strtod(const char *str, char **endptr); |
strtof / 字符串转浮点 / String to Float
| 项目 / Item |
内容 |
| 原型 / Prototype |
float strtof(const char *str, char **endptr); |
rand / 随机数 / Random Number
| 项目 / Item |
内容 |
| 原型 / Prototype |
int rand(void); |
| 说明 / Description |
返回 [0, RAND_MAX] 伪随机整数。Returns pseudo-random integer in [0, RAND_MAX]. |
| 安全 / Safety |
⚠️ 质量低,不适用于密码学。现代替代:arc4random 或 |
srand / 设置随机种子 / Seed Random Generator
| 项目 / Item |
内容 |
| 原型 / Prototype |
void srand(unsigned int seed); |
| 说明 / Description |
设置 rand 的种子。通常 srand(time(NULL))。 |
arc4random / 安全随机数 / Secure Random (BSD)
| 项目 / Item |
内容 |
| 头文件 / Header |
<stdlib.h> (BSD / macOS) |
| 原型 / Prototype |
uint32_t arc4random(void); |
| 说明 / Description |
返回 [0, 2^32-1] 伪随机数,无需手动播种。Returns pseudo-random uint32, auto-seeded. |
qsort / 快速排序 / Quick Sort
| 项目 / Item |
内容 |
| 原型 / Prototype |
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); |
| 说明 / Description |
对数组排序。Sorts array using comparison function. |
| 参数 / Parameters |
base - 数组起始; nmemb - 元素数; size - 元素大小; compar - 比较函数(返回 <0/0/>0) |
| 复杂度 / Complexity |
O(n log n) 平均 |
int cmp(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int arr[] = {3, 1, 4, 1, 5};
qsort(arr, 5, sizeof(int), cmp);
bsearch / 二分搜索 / Binary Search
| 项目 / Item |
内容 |
| 原型 / Prototype |
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); |
| 说明 / Description |
在已排序数组中二分查找。Binary search in sorted array. |
| 返回值 / Return |
匹配元素的指针,未找到返回 NULL |
| 复杂度 / Complexity |
O(log n) |
| 前提 / Requirement |
数组必须已排序 / Array must be sorted |
abs / labs / llabs / 绝对值 / Absolute Value
| 项目 / Item |
内容 |
| 原型 / Prototype |
int abs(int j); / long labs(long j); / long long llabs(long long j); |
| 说明 / Description |
返回绝对值。Returns absolute value. |
| 安全 / Safety |
⚠️ abs(INT_MIN) 结果未定义(溢出) |
div / ldiv / 整数除法 / Integer Division
| 项目 / Item |
内容 |
| 原型 / Prototype |
div_t div(int numer, int denom); / ldiv_t ldiv(long numer, long denom); |
| 说明 / Description |
同时计算商和余数。Computes quotient and remainder. |
| 返回值 / Return |
div_t { quot, rem } 结构体 |
exit / 程序退出 / Program Exit
| 项目 / Item |
内容 |
| 原型 / Prototype |
void exit(int status); / _Exit(int status); |
| 说明 / Description |
正常终止程序,调用 atexit 注册的函数并刷新缓冲区。_Exit 不调用清理函数。 |
abort / 异常终止 / Abnormal Termination
| 项目 / Item |
内容 |
| 原型 / Prototype |
void abort(void); |
| 说明 / Description |
异常终止程序,生成 core dump。Abnormal termination, raises SIGABRT. |
atexit / 退出注册 / Exit Registration
| 项目 / Item |
内容 |
| 原型 / Prototype |
int atexit(void (*func)(void)); |
| 说明 / Description |
注册程序正常退出时调用的函数。Registers function to be called on normal exit. |
system / 执行系统命令 / Execute System Command
| 项目 / Item |
内容 |
| 原型 / Prototype |
int system(const char *command); |
| 说明 / Description |
执行 shell 命令。Executes shell command. |
| 安全 / Safety |
⚠️ 命令注入风险,避免拼接用户输入 |
getenv / 获取环境变量 / Get Environment Variable
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *getenv(const char *name); |
| 说明 / Description |
获取环境变量值。返回的指针不应被修改或释放。Returns environment variable value. |
| 返回值 / Return |
环境变量值的指针,不存在返回 NULL |
<stdio.h> / 输入输出 / Input/Output
printf / 格式化输出 / Formatted Output
| 项目 / Item |
内容 |
| 头文件 / Header |
<stdio.h> / <cstdio> |
| 原型 / Prototype |
int printf(const char *format, ...); |
| 说明 / Description |
格式化输出到 stdout。Writes formatted output to stdout. |
| 返回值 / Return |
输出的字符数,出错返回负数 |
| 常用格式 / Common Formats |
%d int, %ld long, %lld long long, %u unsigned, %f double, %.2f 保留2位, %e 科学计数, %x 十六进制, %o 八进制, %s 字符串, %c 字符, %p 指针, %% 百分号, %zu size_t |
printf("Name: %s, Age: %d, PI: %.2f\n", "Alice", 30, 3.14159);
fprintf / 文件格式化输出 / File Formatted Output
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fprintf(FILE *stream, const char *format, ...); |
| 说明 / Description |
格式化输出到文件流。Writes formatted output to stream. |
sprintf / 字符串格式化 / String Format
| 项目 / Item |
内容 |
| 原型 / Prototype |
int sprintf(char *str, const char *format, ...); |
| 说明 / Description |
格式化输出到字符串。Writes formatted output to string buffer. |
| 安全 / Safety |
⚠️ 缓冲区溢出风险,推荐 snprintf |
snprintf / 安全字符串格式化 / Safe String Format
| 项目 / Item |
内容 |
| 原型 / Prototype |
int snprintf(char *str, size_t size, const char *format, ...); |
| 说明 / Description |
最多写入 size-1 字节,始终 \0 结尾。返回需要的总长度。Writes up to size-1 bytes, always null-terminated. |
| 安全 / Safety |
✅ 安全 |
char buf[32];
int needed = snprintf(buf, sizeof(buf), "value=%d", 42);
if (needed >= sizeof(buf)) { /* 被截断 */ }
scanf / 格式化输入 / Formatted Input
| 项目 / Item |
内容 |
| 原型 / Prototype |
int scanf(const char *format, ...); |
| 说明 / Description |
从 stdin 格式化读取。Reads formatted input from stdin. |
| 返回值 / Return |
成功匹配的项数 |
| 安全 / Safety |
⚠️ 缓冲区溢出风险,建议用宽度限定符 %99s |
int n;
scanf("%d", &n);
char name[100];
scanf("%99s", name); // 限制宽度
fopen / 打开文件 / Open File
| 项目 / Item |
内容 |
| 原型 / Prototype |
FILE *fopen(const char *pathname, const char *mode); |
| 说明 / Description |
打开文件。Opens a file. |
| 模式 / Modes |
"r" 读, "w" 写(截断), "a" 追加, "r+" 读+写, "w+" 写+读(截断), "a+" 追加+读, "rb"/"wb" 二进制模式 |
| 返回值 / Return |
FILE 指针,失败返回 NULL |
FILE *f = fopen("data.txt", "r");
if (!f) { perror("fopen"); return 1; }
fclose / 关闭文件 / Close File
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fclose(FILE *stream); |
| 说明 / Description |
关闭文件流,刷新缓冲区。Closes file stream, flushes buffers. |
fread / 读取数据块 / Read Block
| 项目 / Item |
内容 |
| 原型 / Prototype |
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); |
| 说明 / Description |
从文件读取 nmemb 个大小为 size 的元素。Reads array of elements from file. |
| 返回值 / Return |
实际读取的元素数 |
int arr[10];
size_t n = fread(arr, sizeof(int), 10, f);
fwrite / 写入数据块 / Write Block
| 项目 / Item |
内容 |
| 原型 / Prototype |
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); |
| 说明 / Description |
向文件写入 nmemb 个大小为 size 的元素。Writes array of elements to file. |
fseek / 文件定位 / File Seek
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fseek(FILE *stream, long offset, int whence); |
| 说明 / Description |
设置文件位置。Sets file position. |
| whence |
SEEK_SET 文件开头, SEEK_CUR 当前位置, SEEK_END 文件末尾 |
ftell / 获取文件位置 / Get File Position
| 项目 / Item |
内容 |
| 原型 / Prototype |
long ftell(FILE *stream); |
| 说明 / Description |
返回当前文件位置。Returns current file position. |
rewind / 重置文件位置 / Rewind File
| 项目 / Item |
内容 |
| 原型 / Prototype |
void rewind(FILE *stream); |
| 说明 / Description |
等价于 fseek(stream, 0, SEEK_SET); clearerr(stream); |
fflush / 刷新缓冲区 / Flush Buffer
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fflush(FILE *stream); |
| 说明 / Description |
刷新输出缓冲区。Flushing stdout for output. fflush(NULL) 刷新所有流。 |
fgets / 读取一行 / Read Line
| 项目 / Item |
内容 |
| 原型 / Prototype |
char *fgets(char *s, int size, FILE *stream); |
| 说明 / Description |
最多读取 size-1 个字符,包含 \n,始终 \0 结尾。Reads at most size-1 chars including newline. |
| 返回值 / Return |
成功返回 s,EOF 或错误返回 NULL |
| 安全 / Safety |
✅ 安全 |
char line[256];
while (fgets(line, sizeof(line), f)) {
printf("%s", line);
}
fputs / 写入字符串 / Write String
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fputs(const char *s, FILE *stream); |
| 说明 / Description |
写入字符串到文件(不追加 \n)。Writes string to stream. |
fgetc / 读取单个字符 / Read Single Character
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fgetc(FILE *stream); |
| 说明 / Description |
读取下一个字符。返回 int 以区分 EOF。Reads next character as int. |
| 返回值 / Return |
字符(unsigned char 转为 int),EOF 表示结束或错误 |
fputc / 写入单个字符 / Write Single Character
| 项目 / Item |
内容 |
| 原型 / Prototype |
int fputc(int c, FILE *stream); |
| 说明 / Description |
写入一个字符到文件。Writes a character to stream. |
ungetc / 回退字符 / Push Back Character
| 项目 / Item |
内容 |
| 原型 / Prototype |
int ungetc(int c, FILE *stream); |
| 说明 / Description |
将字符推回流,下次读取会先读到它。Pushes character back to stream. |
feof / 检测文件结束 / Check End of File
| 项目 / Item |
内容 |
| 原型 / Prototype |
int feof(FILE *stream); |
| 说明 / Description |
检测是否到达文件末尾。Returns true if EOF flag is set. |
ferror / 检测错误 / Check Error
| 项目 / Item |
内容 |
| 原型 / Prototype |
int ferror(FILE *stream); |
| 说明 / Description |
检测是否发生错误。Returns true if error flag is set. |
remove / 删除文件 / Remove File
| 项目 / Item |
内容 |
| 原型 / Prototype |
int remove(const char *pathname); |
| 说明 / Description |
删除文件或空目录。Deletes file or empty directory. |
rename / 重命名 / Rename File
| 项目 / Item |
内容 |
| 原型 / Prototype |
int rename(const char *oldpath, const char *newpath); |
| 说明 / Description |
重命名或移动文件。Renames or moves a file. |
popen / 管道打开 / Pipe Open
| 项目 / Item |
内容 |
| 原型 / Prototype |
FILE *popen(const char *command, const char *type); |
| 说明 / Description |
创建管道并执行命令。Creates pipe to/from command. |
| type |
"r" 读取命令输出, "w" 写入命令输入 |
FILE *fp = popen("ls -la", "r");
char line[256];
while (fgets(line, sizeof(line), fp)) puts(line);
pclose(fp);
<math.h> / 数学 / Mathematics
fabs / 绝对值(浮点)/ Absolute Value (Float)
| 项目 / Item |
内容 |
| 头文件 / Header |
<math.h> / <cmath> |
| 原型 / Prototype |
double fabs(double x); / float fabsf(float); / long double fabsl(long double); |
| 说明 / Description |
返回浮点绝对值。Returns floating-point absolute value. |
fmod / 浮点取模 / Float Modulo
| 项目 / Item |
内容 |
| 原型 / Prototype |
double fmod(double x, double y); |
| 说明 / Description |
返回 x/y 的浮点余数。Returns floating-point remainder of x/y. |
floor / ceil / trunc / round / 取整函数 / Rounding Functions
| 项目 / Item |
内容 |
| 原型 / Prototype |
double floor(double x); double ceil(double x); double trunc(double x); double round(double x); |
| 说明 / Description |
floor 向下取整 / round down; ceil 向上取整 / round up; trunc 向零取整 / toward zero; round 四舍五入 / round to nearest |
floor(3.7) // 3.0
ceil(3.2) // 4.0
trunc(-3.7) // -3.0
round(3.5) // 4.0
sqrt / 平方根 / Square Root
| 项目 / Item |
内容 |
| 原型 / Prototype |
double sqrt(double x); |
| 说明 / Description |
返回非负平方根。Returns non-negative square root. |
| 注意 / Note |
负数返回 NaN |
pow / 幂运算 / Power
| 项目 / Item |
内容 |
| 原型 / Prototype |
double pow(double base, double exponent); |
| 说明 / Description |
返回 base^exponent。Returns base raised to exponent. |
exp / log / log2 / log10 / 指数与对数 / Exponential and Logarithm
| 项目 / Item |
内容 |
| 原型 / Prototype |
double exp(double x); double log(double x); double log2(double x); double log10(double x); |
| 说明 / Description |
exp e^x; log 自然对数 ln(x); log2 log₂(x); log10 log₁₀(x) |
sin / cos / tan / 三角函数 / Trigonometric Functions
| 项目 / Item |
内容 |
| 原型 / Prototype |
double sin(double x); double cos(double x); double tan(double x); |
| 说明 / Description |
参数为弧度。Arguments in radians. |
asin / acos / atan / atan2 / 反三角函数 / Inverse Trigonometric
| 项目 / Item |
内容 |
| 原型 / Prototype |
double asin(double x); double acos(double x); double atan(double y, double x); |
| 说明 / Description |
asin [-1,1]→[-π/2,π/2]; acos [-1,1]→[0,π]; atan2(y,x) 返回 atan(y/x) 并正确处理象限 |
isnan / isinf / isfinite / 浮点分类 / Float Classification
| 项目 / Item |
内容 |
| 头文件 / Header |
<math.h> (C99) |
| 原型 / Prototype |
int isnan(double x); int isinf(double x); int isfinite(double x); |
| 说明 / Description |
检测 NaN、无穷大、有限值。Detects NaN, infinity, finite values. |
copysign / 复制符号 / Copy Sign
| 项目 / Item |
内容 |
| 原型 / Prototype |
double copysign(double x, double y); |
| 说明 / Description |
返回 x 的绝对值与 y 的符号组合。Returns magnitude of x with sign of y. |
数学常量 / Math Constants
| 常量 / Constant |
值 / Value |
说明 |
M_PI |
3.14159265358979323846 |
π |
M_E |
2.71828182845904523536 |
e |
HUGE_VAL |
double 正无穷 |
正无穷大 |
INFINITY |
float/double 正无穷 |
正无穷大 |
NAN |
NaN |
非数值 |
<ctype.h> / 字符分类 / Character Classification
| 函数 / Function |
说明 / Description |
示例 |
int isdigit(int c) |
数字 0-9 / decimal digit |
isdigit('5') → true |
int isxdigit(int c) |
十六进制数字 0-9,a-f,A-F / hex digit |
isxdigit('A') → true |
int isalpha(int c) |
字母 a-z,A-Z / alphabetic |
isalpha('K') → true |
int isalnum(int c) |
字母或数字 / alphanumeric |
isalnum('3') → true |
int isspace(int c) |
空白字符 / whitespace |
isspace(' ') → true |
int isupper(int c) |
大写字母 / uppercase |
isupper('A') → true |
int islower(int c) |
小写字母 / lowercase |
islower('a') → true |
int isprint(int c) |
可打印字符 / printable |
isprint('!') → true |
int ispunct(int c) |
标点符号 / punctuation |
ispunct(',') → true |
int iscntrl(int c) |
控制字符 / control |
iscntrl('\n') → true |
int isgraph(int c) |
图形字符(可打印且非空格)/ graphic |
isgraph('A') → true |
int toupper(int c) |
转大写 / to uppercase |
toupper('a') → 'A' |
int tolower(int c) |
转小写 / to lowercase |
tolower('A') → 'a' |
注意 / Note: 参数应为 unsigned char 或 EOF。传入负值 char(如中文)是未定义行为。
<time.h> / 时间 / Time
time / 获取当前时间 / Get Current Time
| 项目 / Item |
内容 |
| 头文件 / Header |
<time.h> / <ctime> |
| 原型 / Prototype |
time_t time(time_t *tloc); |
| 说明 / Description |
返回当前日历时间(秒数,自 Epoch 1970-01-01)。Returns current calendar time. |
localtime / 本地时间分解 / Local Time Decomposition
| 项目 / Item |
内容 |
| 原型 / Prototype |
struct tm *localtime(const time_t *timep); |
| 说明 / Description |
将 time_t 转为本地时间的 struct tm。Converts to local time broken-down form. |
| 安全 / Safety |
⚠️ 返回静态缓冲区,非线程安全。多线程用 localtime_r |
gmtime / UTC 时间分解 / UTC Time Decomposition
| 项目 / Item |
内容 |
| 原型 / Prototype |
struct tm *gmtime(const time_t *timep); |
| 说明 / Description |
转为 UTC 时间的 struct tm。Converts to UTC time. |
mktime / 时间合成 / Make Time
| 项目 / Item |
内容 |
| 原型 / Prototype |
time_t mktime(struct tm *tm); |
| 说明 / Description |
将 struct tm 转为 time_t。Converts broken-down time to time_t. |
strftime / 时间格式化 / Format Time
| 项目 / Item |
内容 |
| 原型 / Prototype |
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm); |
| 常用格式 / Formats |
%Y 年(4位), %m 月(01-12), %d 日(01-31), %H 时(00-23), %M 分, %S 秒, %F %Y-%m-%d, %T %H:%M:%S, %c 本地日期时间 |
time_t now = time(NULL);
struct tm *t = localtime(&now);
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);
printf("%s\n", buf); // 2024-01-15 14:30:00
clock / 进程 CPU 时间 / Process CPU Time
| 项目 / Item |
内容 |
| 原型 / Prototype |
clock_t clock(void); |
| 说明 / Description |
返回进程使用的 CPU 时间。Returns CPU time used. |
| 常量 |
CLOCKS_PER_SEC 每秒时钟数 |
clock_t start = clock();
// ... 工作 ...
double elapsed = (double)(clock() - start) / CLOCKS_PER_SEC;
struct tm / 分解时间结构 / Broken-down Time Structure
struct tm {
int tm_sec; // 秒 [0,60]
int tm_min; // 分 [0,59]
int tm_hour; // 时 [0,23]
int tm_mday; // 日 [1,31]
int tm_mon; // 月 [0,11] ⚠️ 从0开始
int tm_year; // 年-1900
int tm_wday; // 星期 [0,6] 0=周日
int tm_yday; // 一年中的第几天 [0,365]
int tm_isdst; // 夏令时标志
};
<signal.h> / 信号 / Signals
| 函数 / Function |
说明 / Description |
void (*signal(int sig, void (*handler)(int)))(int); |
设置信号处理函数 / Set signal handler |
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact); |
POSIX 信号处理(推荐)/ POSIX signal handling (recommended) |
int kill(pid_t pid, int sig); |
向进程发送信号 / Send signal to process |
int raise(int sig); |
向自身发送信号 / Send signal to self |
unsigned int alarm(unsigned int seconds); |
设置定时 SIGALRM / Schedule SIGALRM |
常用信号 / Common Signals
| 信号 / Signal |
值 / Value |
说明 / Description |
SIGINT |
2 |
中断 (Ctrl+C) / Interrupt |
SIGTERM |
15 |
终止请求 / Termination |
SIGKILL |
9 |
强制终止(不可捕获)/ Kill (uncatchable) |
SIGSEGV |
11 |
段错误 / Segmentation fault |
SIGPIPE |
13 |
管道破裂(写已关闭的管道)/ Broken pipe |
SIGCHLD |
20 |
子进程状态变化 / Child status change |
SIGALRM |
14 |
定时器到期 / Alarm clock |
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
volatile sig_atomic_t running = 1;
void handler(int sig) { running = 0; }
int main() {
signal(SIGINT, handler);
while (running) { pause(); }
printf("退出\n");
}
<assert.h> / 断言 / Assertions
| 项目 / Item |
内容 |
| 头文件 / Header |
<assert.h> / <cassert> |
| 宏 / Macro |
void assert(scalar expression); |
| 说明 / Description |
表达式为 0 时打印诊断信息并调用 abort()。Aborts if expression is false. |
| 禁用 / Disable |
定义 NDEBUG 宏可禁用所有 assert。#define NDEBUG before include disables all asserts. |
#include <assert.h>
void process(int *p) {
assert(p != NULL); // p 为 NULL 时终止
// ...
}
<errno.h> / 错误码 / Error Codes
| 项目 / Item |
内容 |
| 头文件 / Header |
<errno.h> / <cerrno> |
| 变量 / Variable |
int errno; — 由库函数设置的全局错误码 |
| 函数 |
void perror(const char *s); — 打印 errno 对应的错误信息到 stderr |
| 函数 |
char *strerror(int errnum); — 返回错误描述字符串 |
常见错误码 / Common Error Codes
| 错误码 / Code |
值 / Value |
说明 / Description |
EINVAL |
22 |
无效参数 / Invalid argument |
ENOMEM |
12 |
内存不足 / Out of memory |
ENOENT |
2 |
文件或目录不存在 / No such file |
EACCES |
13 |
权限不足 / Permission denied |
EINTR |
4 |
被信号中断 / Interrupted system call |
EAGAIN / EWOULDBLOCK |
35 / 11 |
资源暂时不可用 / Resource temporarily unavailable |
EPERM |
1 |
操作不允许 / Operation not permitted |
#include <errno.h>
FILE *f = fopen("nonexistent.txt", "r");
if (!f) {
perror("fopen"); // fopen: No such file or directory
printf("errno=%d\n", errno); // errno=2
}
<stdint.h> / 定宽整数 / Fixed-Width Integers
| 类型 / Type |
说明 / Description |
int8_t ~ int64_t |
有符号 8/16/32/64 位整数 / Signed fixed-width |
uint8_t ~ uint64_t |
无符号 8/16/32/64 位整数 / Unsigned fixed-width |
intptr_t / uintptr_t |
可容纳指针的整数 / Integer type holding a pointer |
size_t |
sizeof 返回的无符号类型 / Unsigned type from sizeof |
ptrdiff_t |
指针差值的有符号类型 / Signed pointer difference |
intmax_t / uintmax_t |
最大宽度整数 / Maximum width integer |
极限宏 / Limit Macros
| 宏 / Macro |
说明 / Description |
INT8_MIN / INT8_MAX |
int8_t 最小/最大值 |
INT64_MIN / INT64_MAX |
int64_t 范围: -2^63 ~ 2^63-1 |
UINT64_MAX |
2^64 - 1 = 18446744073709551615 |
SIZE_MAX |
size_t 最大值 |
<stddef.h> / 标准定义 / Standard Definitions
| 项目 / Item |
内容 |
size_t |
sizeof 运算符结果的无符号整数类型 |
ptrdiff_t |
两个指针差值的有符号整数类型 |
offsetof(type, member) |
结构体成员偏移量(字节) |
NULL |
空指针常量 |
max_align_t |
最大对齐要求的类型 |
<stdbool.h> / 布尔 / Boolean
| 项目 / Item |
内容 |
bool |
布尔类型(展开为 _Bool) |
true |
展开为 1 |
false |
展开为 0 |
__bool_true_false_are_defined |
展开为 1 |
C++ 中 bool/true/false 是内置关键字,无需此头文件。
<inttypes.h> / 格式化宏 / Formatting Macros
用于 printf/scanf 打印 int64_t 等定宽类型。
| 宏 / Macro |
用途 / Usage |
示例 |
PRId64 |
printf int64_t |
printf("%" PRId64, val); |
PRIu64 |
printf uint64_t |
printf("%" PRIu64, val); |
PRIX64 |
printf uint64_t 十六进制大写 |
printf("%" PRIX64, val); |
SCNd64 |
scanf int64_t |
scanf("%" SCNd64, &val); |
<limits.h> / 极限值 / Limits
| 宏 / Macro |
说明 / Description |
CHAR_BIT |
char 的位数(通常 8) |
INT_MIN / INT_MAX |
int 范围: -32768 ~ 32767 (16位) 或 -2^31 ~ 2^31-1 (32位) |
LONG_MAX |
long 最大值 |
LLONG_MAX |
long long 最大值: 2^63-1 |
MB_LEN_MAX |
多字节字符最大字节数 |
UCHAR_MAX |
unsigned char 最大值: 255 |
USHRT_MAX |
unsigned short 最大值: 65535 |
UINT_MAX |
unsigned int 最大值 |
ULONG_MAX |
unsigned long 最大值 |
<float.h> / 浮点极限 / Floating-Point Limits
| 宏 / Macro |
说明 / Description |
FLT_MIN / FLT_MAX |
float 最小/最大正规值 |
DBL_MIN / DBL_MAX |
double 最小/最大正规值 |
FLT_EPSILON |
float 最小可表示差值(≈1.19e-7) |
DBL_EPSILON |
double 最小可表示差值(≈2.22e-16) |
LDBL_DIG |
long double 十进制精度位数 |
FLT_DIG / DBL_DIG |
十进制精度位数(6 / 15) |
DECIMAL_DIG |
最宽类型十进制精度 |
C++ 标准库 (C++ Standard Library / C++ 标准库)
字符串 / Strings
std::string 构造与基本操作 / Construction & Basics
| 操作 / Operation |
说明 / Description |
示例 |
string s; |
默认构造,空字符串 |
|
string s("hello"); |
C 字符串构造 |
|
string s(5, 'a'); |
5 个 'a' → "aaaaa" |
|
string s2 = s; |
拷贝构造 |
|
string s3 = std::move(s); |
移动构造 / Move construct |
|
s = "world"; |
赋值 / Assign |
|
s.empty() |
是否为空 / Is empty |
s.empty() → false |
s.size() / s.length() |
字符数 / Character count |
|
s.capacity() |
已分配容量 / Allocated capacity |
|
s.reserve(100) |
预留容量(不改变 size)/ Reserve capacity |
|
s.shrink_to_fit() |
释放多余容量 / Release excess capacity (C++11) |
|
s.c_str() |
返回 C 字符串(const char*) |
|
s.data() |
返回可修改的字符数组指针 (C++17) |
|
连接与比较 / Concatenation & Comparison
| 操作 / Operation |
说明 / Description |
s1 + s2 |
连接 / Concatenation |
s += "x" |
追加 / Append |
s.append("xyz") |
追加字符串 |
s.push_back('a') |
追加单个字符 |
s1 == s2 / s1 != s2 |
相等比较 / Equality |
s1 < s2 / s1 > s2 |
字典序比较 / Lexicographic |
s1.compare(s2) |
比较函数(<0/0/>0) |
查找 / Searching
| 操作 / Operation |
说明 / Description |
复杂度 |
s.find("ab") |
查找子串首次出现位置 / First occurrence |
O(n*m) |
s.rfind("ab") |
查找子串最后出现位置 / Last occurrence |
O(n*m) |
s.find_first_of("aeiou") |
查找任一字符首次出现 |
O(n) |
s.find_last_of("aeiou") |
查找任一字符最后出现 |
O(n) |
s.find_first_not_of("abc") |
查找不在集合中的首个字符 |
O(n) |
s.substr(pos, len) |
提取子串 / Extract substring |
O(n) |
| 返回值 |
string::npos 表示未找到 |
|
修改 / Modification
| 操作 / Operation |
说明 / Description |
s.insert(pos, "str") |
在 pos 插入 |
s.erase(pos, len) |
删除从 pos 开始的 len 个字符 |
s.replace(pos, len, "new") |
替换 |
s.clear() |
清空 |
字符串转换 / String Conversion (C++11)
| 函数 / Function |
说明 / Description |
std::stoi(s) |
字符串→int |
std::stol(s) |
字符串→long |
std::stoll(s) |
字符串→long long |
std::stoul(s) |
字符串→unsigned long |
std::stod(s) |
字符串→double |
std::stof(s) |
字符串→float |
std::to_string(42) |
数值→string |
std::string_view (C++17) / 字符串视图
| 项目 / Item |
内容 |
| 头文件 / Header |
<string_view> |
| 说明 / Description |
非拥有字符串视图,零拷贝引用字符串片段。Non-owning reference to string. |
| 操作 / Operation |
说明 / Description |
string_view sv("hello"); |
构造 |
sv.substr(pos, len) |
子串视图 / Sub-view |
sv.starts_with("he") |
前缀匹配 (C++20) |
sv.ends_with("lo") |
后缀匹配 (C++20) |
sv.find("ll") |
查找 |
sv.compare(sv2) |
比较 |
sv.size() / sv.length() |
长度 |
sv.data() |
底层数据指针 |
sv.empty() |
是否为空 |
void process(std::string_view sv) {
// 无拷贝地处理字符串片段
if (sv.starts_with("http")) { /* ... */ }
}
process("https://example.com");
std::string s = "hello";
process(s); // 隐式转换
动态数组 / Dynamic Arrays
构造与基本操作 / Construction & Basics
| 操作 / Operation |
说明 / Description |
复杂度 |
vector<int> v; |
默认构造,空 |
O(1) |
vector<int> v(100); |
100 个默认值元素 |
O(n) |
vector<int> v(10, 42); |
10 个值为 42 |
O(n) |
vector<int> v{1,2,3}; |
初始化列表 (C++11) |
O(n) |
vector<int> v2(v); |
拷贝构造 |
O(n) |
vector<int> v3(std::move(v)); |
移动构造 |
O(1) |
元素访问 / Element Access
| 操作 / Operation |
说明 / Description |
v[i] |
下标访问(无边界检查)/ No bounds check |
v.at(i) |
带边界检查,越界抛 out_of_range / Bounds checked |
v.front() |
第一个元素 |
v.back() |
最后一个元素 |
v.data() |
底层数组指针 |
v.size() |
元素个数 |
v.capacity() |
已分配容量 |
v.empty() |
是否为空 |
修改 / Modification
| 操作 / Operation |
说明 / Description |
复杂度 |
迭代器失效 |
v.push_back(x) |
末尾添加 |
均摊 O(1) |
可能全部失效 |
v.emplace_back(args...) |
原地构造末尾元素 (C++11) |
均摊 O(1) |
可能全部失效 |
v.pop_back() |
移除末尾元素 |
O(1) |
仅 end() 失效 |
v.insert(pos, x) |
在 pos 处插入 |
O(n) |
pos 及之后失效 |
v.erase(pos) |
删除 pos 处元素 |
O(n) |
pos 及之后失效 |
v.resize(n) |
调整大小(新元素默认值) |
O(n) |
可能全部失效 |
v.reserve(n) |
预留容量(不改变 size) |
O(n) 最坏 |
不失效 |
v.shrink_to_fit() |
释放多余容量 (C++11) |
O(n) |
不失效 |
v.clear() |
清空所有元素 |
O(n) |
全部失效 |
v.swap(v2) |
交换内容 |
O(1) |
引用其他容器失效 |
迭代器 / Iterators
| 操作 / Operation |
说明 / Description |
v.begin() / v.end() |
正向迭代器 |
v.rbegin() / v.rend() |
反向迭代器 |
v.cbegin() / v.cend() |
const 迭代器 |
迭代器失效规则 / Iterator Invalidation Rules
push_back / emplace_back:若发生重分配(size == capacity),所有迭代器/指针/引用失效
insert:插入点及之后的所有失效
erase:删除点及之后的所有失效
pop_back:仅 end() 失效
resize:若增大则可能全部失效
reserve / shrink_to_fit:可能全部失效
二维 vector / 2D Vector
vector<vector<int>> matrix(3, vector<int>(4, 0)); // 3×4 全零
matrix[1][2] = 42;
for (auto& row : matrix) {
for (auto& val : row) {
cout << val << " ";
}
cout << "\n";
}
/ 链表 / Linked Lists
| 操作 / Operation |
list |
forward_list |
说明 / Description |
push_back(x) |
✅ |
❌ |
末尾添加 |
push_front(x) |
✅ |
✅ |
头部添加 O(1) |
pop_back() |
✅ |
❌ |
移除末尾 |
pop_front() |
✅ |
✅ |
移除头部 O(1) |
insert(pos, x) |
✅ |
✅ |
插入 O(1) |
erase(pos) |
✅ |
✅ |
删除 O(1) |
splice(pos, other) |
✅ |
✅ |
转移节点 O(1) |
sort() |
✅ |
✅ |
排序 O(n log n) |
unique() |
✅ |
✅ |
去除连续重复 O(n) |
merge(other) |
✅ |
✅ |
合并有序链表 O(n) |
reverse() |
✅ |
✅ |
反转 O(n) |
remove(val) |
✅ |
✅ |
移除所有等于 val 的元素 O(n) |
链表特点:任意位置插入/删除 O(1),不支持随机访问,缓存不友好。
双端队列 / Double-Ended Queue
| 操作 / Operation |
说明 / Description |
复杂度 |
push_front(x) / push_back(x) |
头/尾添加 |
O(1) |
pop_front() / pop_back() |
头/尾移除 |
O(1) |
d[i] / d.at(i) |
随机访问 |
O(1) |
d.front() / d.back() |
首/尾元素 |
O(1) |
d.insert(pos, x) |
插入 |
O(n) |
d.size() / d.empty() |
大小/判空 |
O(1) |
deque 内存为分段连续,支持 O(1) 首尾操作和随机访问。中间插入仍为 O(n)。
/ 关联容器 / Associative Containers
std::map(有序映射)/ Ordered Map
| 操作 / Operation |
说明 / Description |
复杂度 |
m[key] = val |
插入或更新(不存在时默认构造)/ Insert or update |
O(log n) |
m.at(key) |
访问,不存在抛异常 / Access with bounds check |
O(log n) |
m.insert({key, val}) |
插入,返回 pair<iterator,bool> |
O(log n) |
m.emplace(key, val) |
原地插入 (C++11) |
O(log n) |
m.erase(key) |
按键删除 |
O(log n) |
m.erase(it) |
按迭代器删除 |
O(1) 均摊 |
m.find(key) |
查找,返回迭代器 |
O(log n) |
| `m.count |
|
|
…(truncated)
1---2name: cppreference3description: C/C++ 标准库 API 速查 / C/C++ Standard Library Quick Reference4---5# C/C++ 标准库 API 速查 / C/C++ Standard Library Quick Reference67> 中英双语速查手册,涵盖 C 标准库与 C++ 标准库核心 API。8> Bilingual quick reference covering C and C++ standard library core APIs.9>10> 参考:cppreference.com / cppreference.cn / c.biancheng.net1112---1314# 目录 / Table of Contents1516- [C 标准库](#c-标准库-c-standard-library)17 - [<string.h> 字符串操作](#stringh--cstring-字符串操作--string-operations)18 - [<stdlib.h> 通用工具](#stdlibh--cstdlib-通用工具--general-utilities)19 - [<stdio.h> 输入输出](#stdioh--cstdio-输入输出--inputoutput)20 - [<math.h> 数学](#mathh--cmath-数学--mathematics)21 - [<ctype.h> 字符分类](#ctypeh--cctype-字符分类--character-classification)22 - [<time.h> 时间](#timeh--ctime-时间--time)23 - [<signal.h> 信号](#signalh--csignal-信号--signals)24 - [<assert.h> 断言](#asserth--cassert-断言--assertions)25 - [<errno.h> 错误码](#errnoh--cerrno-错误码--error-codes)26 - [<stdint.h> 定宽整数](#stdinth--cstdint-定宽整数--fixed-width-integers)27 - [<stddef.h> 标准定义](#stddefh--cstddef-标准定义--standard-definitions)28 - [<stdbool.h> 布尔](#stdboolh--cstdbool-布尔--boolean)29 - [<inttypes.h> 格式化宏](#inttypesh--cinttypes-格式化宏--formatting-macros)30 - [<limits.h> 极限值](#limitsh--climits-极限值--limits)31 - [<float.h> 浮点极限](#floath--cfloat-浮点极限--floating-point-limits)32- [C++ 标准库](#c-标准库-c-standard-library-1)33 - [<string> 字符串](#string-字符串--strings)34 - [<vector> 动态数组](#vector-动态数组--dynamic-arrays)35 - [<list>/<forward_list> 链表](#list--forward_list-链表--linked-lists)36 - [<deque> 双端队列](#deque-双端队列--double-ended-queue)37 - [<map>/<unordered_map> 关联容器](#map--unordered_map-关联容器--associative-containers)38 - [<set>/<unordered_set>](#set--unordered_set-集合--sets)39 - [<array>/<span>](#array--span-固定数组与视图--fixed-array-and-view)40 - [<algorithm> 算法](#algorithm-算法--algorithms)41 - [<numeric> 数值算法](#numeric-数值算法--numeric-algorithms)42 - [<memory> 内存](#memory-内存--memory)43 - [<functional> 函数对象](#functional-函数对象--function-objects)44 - [<thread> 线程](#thread-线程--threading)45 - [<mutex> 互斥量](#mutex-互斥量--mutexes)46 - [<condition_variable> 条件变量](#condition_variable-条件变量--condition-variables)47 - [<future> 异步](#future-异步--futures)48 - [<atomic> 原子操作](#atomic-原子操作--atomic-operations)49 - [<chrono> 时间](#chrono-时间--time)50 - [<optional>/<variant>/<any>](#optional--variant--any-可选类型--optional-types)51 - [<tuple> 元组](#tuple-元组--tuples)52 - [<filesystem> 文件系统](#filesystem-文件系统-c17--filesystem-c17)53 - [<format> 格式化](#format-格式化-c20--format-c20)54 - [<regex> 正则表达式](#regex-正则表达式--regular-expressions)55 - [<iostream>/<fstream>/<sstream>](#iostream--fstream--sstream-流--io-streams)56 - [<stdexcept> 异常](#stdexcept-异常--exceptions)57 - [<type_traits> 类型特性](#type_traits-类型特性--type-traits)58 - [<utility>](#utility-通用工具--utility)59 - [<bitset>](#bitset-位集--bitsets)60 - [<valarray> 数值数组](#valarray-数值数组--numeric-arrays)61- [开发经验与调优](#开发经验与调优-development-tips)6263---6465# C 标准库 (C Standard Library / C 标准库)6667---6869## <string.h> / <cstring> 字符串操作 / String Operations7071### memcpy / 内存拷贝 / Memory Copy7273| 项目 / Item | 内容 |74|---|---|75| **头文件 / Header** | `<string.h>` / `<cstring>` |76| **原型 / Prototype** | `void *memcpy(void *dest, const void *src, size_t n);` |77| **说明 / Description** | 从 `src` 复制 `n` 字节到 `dest`。源和目标内存区域不可重叠。Copies `n` bytes from `src` to `dest`. Regions must not overlap. |78| **参数 / Parameters** | `dest` - 目标指针 / destination pointer; `src` - 源指针 / source pointer; `n` - 字节数 / byte count |79| **返回值 / Return** | `dest` 指针 |80| **复杂度 / Complexity** | O(n) |81| **安全 / Safety** | ⚠️ 内存重叠时行为未定义,重叠区域用 `memmove` |8283```c84char src[] = "hello";85char dst[6];86memcpy(dst, src, 6); // dst == "hello"87```8889### memmove / 安全内存拷贝 / Safe Memory Copy9091| 项目 / Item | 内容 |92|---|---|93| **头文件 / Header** | `<string.h>` / `<cstring>` |94| **原型 / Prototype** | `void *memmove(void *dest, const void *src, size_t n);` |95| **说明 / Description** | 从 `src` 复制 `n` 字节到 `dest`,源和目标可以重叠。Copies `n` bytes; handles overlapping regions. |96| **参数 / Parameters** | 同 memcpy |97| **返回值 / Return** | `dest` |98| **复杂度 / Complexity** | O(n) |99100```c101char buf[] = "abcdef";102memmove(buf + 2, buf, 4); // buf == "ababcd"103```104105### memset / 内存填充 / Memory Set106107| 项目 / Item | 内容 |108|---|---|109| **头文件 / Header** | `<string.h>` / `<cstring>` |110| **原型 / Prototype** | `void *memset(void *dest, int c, size_t n);` |111| **说明 / Description** | 将 `dest` 的前 `n` 字节设为 `c`(转为 unsigned char)。Sets first `n` bytes of `dest` to `c`. |112| **参数 / Parameters** | `dest` - 目标; `c` - 填充值; `n` - 字节数 |113| **返回值 / Return** | `dest` |114| **复杂度 / Complexity** | O(n) |115116```c117int arr[10];118memset(arr, 0, sizeof(arr)); // 全部置零 / zero-fill119```120121### memcmp / 内存比较 / Memory Compare122123| 项目 / Item | 内容 |124|---|---|125| **头文件 / Header** | `<string.h>` / `<cstring>` |126| **原型 / Prototype** | `int memcmp(const void *s1, const void *s2, size_t n);` |127| **说明 / Description** | 比较前 `n` 字节。Compares first `n` bytes. 返回 <0/0/>0 表示 s1 小于/等于/大于 s2。 |128| **返回值 / Return** | 负数/0/正数 |129| **复杂度 / Complexity** | O(n) |130131### memchr / 内存搜索 / Memory Character Search132133| 项目 / Item | 内容 |134|---|---|135| **头文件 / Header** | `<string.h>` / `<cstring>` |136| **原型 / Prototype** | `void *memchr(const void *s, int c, size_t n);` |137| **说明 / Description** | 在前 `n` 字节中查找 `c`。Searches for `c` in first `n` bytes. |138| **返回值 / Return** | 找到的指针,未找到返回 NULL |139140### strcpy / 字符串拷贝 / String Copy141142| 项目 / Item | 内容 |143|---|---|144| **头文件 / Header** | `<string.h>` / `<cstring>` |145| **原型 / Prototype** | `char *strcpy(char *dest, const char *src);` |146| **说明 / Description** | 将 `src`(含 `\0`)复制到 `dest`。Copies `src` including null terminator to `dest`. |147| **安全 / Safety** | ⚠️ 缓冲区溢出风险,推荐 `strncpy` 或 `snprintf` |148149```c150char dst[20];151strcpy(dst, "hello");152```153154### strncpy / 有限字符串拷贝 / Bounded String Copy155156| 项目 / Item | 内容 |157|---|---|158| **头文件 / Header** | `<string.h>` / `<cstring>` |159| **原型 / Prototype** | `char *strncpy(char *dest, const char *src, size_t n);` |160| **说明 / Description** | 最多复制 `n` 字节。如果 `strlen(src) < n`,剩余字节填充 `\0`。Copies up to `n` bytes. |161| **安全 / Safety** | ⚠️ 不保证以 `\0` 结尾(当 `strlen(src) >= n` 时) |162163### strlcpy / 安全字符串拷贝 / Safe String Copy (BSD)164165| 项目 / Item | 内容 |166|---|---|167| **头文件 / Header** | `<string.h>` (BSD / macOS) |168| **原型 / Prototype** | `size_t strlcpy(char *dest, const char *src, size_t size);` |169| **说明 / Description** | 最多复制 `size-1` 字节,始终保证 `\0` 结尾。返回 `strlen(src)`。Guaranteed null-termination. |170| **安全 / Safety** | ✅ 安全,返回完整源串长度便于截断检测 |171172```c173char buf[8];174strlcpy(buf, "hello world", sizeof(buf)); // buf == "hello w", 返回 11175```176177### strcat / 字符串连接 / String Concatenation178179| 项目 / Item | 内容 |180|---|---|181| **头文件 / Header** | `<string.h>` / `<cstring>` |182| **原型 / Prototype** | `char *strcat(char *dest, const char *src);` |183| **说明 / Description** | 将 `src` 追加到 `dest` 末尾。Appends `src` to `dest`. |184| **安全 / Safety** | ⚠️ 缓冲区溢出风险,推荐 `strncat` 或 `snprintf` |185186### strncat / 有限字符串连接 / Bounded String Concatenation187188| 项目 / Item | 内容 |189|---|---|190| **头文件 / Header** | `<string.h>` / `<cstring>` |191| **原型 / Prototype** | `char *strncat(char *dest, const char *src, size_t n);` |192| **说明 / Description** | 最多追加 `n` 字节,始终以 `\0` 结尾。Appends up to `n` bytes, always null-terminated. |193194### strlcat / 安全字符串连接 / Safe String Concatenation (BSD)195196| 项目 / Item | 内容 |197|---|---|198| **头文件 / Header** | `<string.h>` (BSD / macOS) |199| **原型 / Prototype** | `size_t strlcat(char *dest, const char *src, size_t size);` |200| **说明 / Description** | 安全连接,返回尝试创建的字符串总长度。Safe concatenation, returns total intended length. |201202### strlen / 字符串长度 / String Length203204| 项目 / Item | 内容 |205|---|---|206| **头文件 / Header** | `<string.h>` / `<cstring>` |207| **原型 / Prototype** | `size_t strlen(const char *s);` |208| **说明 / Description** | 返回字符串长度(不含 `\0`)。Returns length excluding null terminator. |209| **返回值 / Return** | 字符串长度 / string length |210| **复杂度 / Complexity** | O(n) |211212### strcmp / 字符串比较 / String Compare213214| 项目 / Item | 内容 |215|---|---|216| **头文件 / Header** | `<string.h>` / `<cstring>` |217| **原型 / Prototype** | `int strcmp(const char *s1, const char *s2);` |218| **说明 / Description** | 按字典序比较。返回 <0/0/>0。Lexicographic comparison. |219| **复杂度 / Complexity** | O(n) |220221### strncmp / 有限字符串比较 / Bounded String Compare222223| 项目 / Item | 内容 |224|---|---|225| **原型 / Prototype** | `int strncmp(const char *s1, const char *s2, size_t n);` |226| **说明 / Description** | 最多比较前 `n` 个字符。Compares up to `n` characters. |227228### strchr / 字符查找(正向)/ Find Character (Forward)229230| 项目 / Item | 内容 |231|---|---|232| **原型 / Prototype** | `char *strchr(const char *s, int c);` |233| **说明 / Description** | 查找 `c` 第一次出现的位置。Finds first occurrence of `c`. |234235### strrchr / 字符查找(反向)/ Find Character (Reverse)236237| 项目 / Item | 内容 |238|---|---|239| **原型 / Prototype** | `char *strrchr(const char *s, int c);` |240| **说明 / Description** | 查找 `c` 最后一次出现的位置。Finds last occurrence of `c`. |241242### strstr / 子串查找 / Substring Search243244| 项目 / Item | 内容 |245|---|---|246| **原型 / Prototype** | `char *strstr(const char *haystack, const char *needle);` |247| **说明 / Description** | 查找 `needle` 在 `haystack` 中首次出现的位置。Finds first occurrence of substring. |248| **返回值 / Return** | 匹配位置的指针,未找到返回 NULL |249| **复杂度 / Complexity** | O(n*m) 最坏情况 |250251```c252const char *s = "hello world";253char *p = strstr(s, "world"); // p 指向 "world"254```255256### strtok / 字符串分割 / String Tokenize257258| 项目 / Item | 内容 |259|---|---|260| **原型 / Prototype** | `char *strtok(char *str, const char *delim);` |261| **说明 / Description** | 按 `delim` 分割字符串。首次调用传字符串,后续传 NULL。Tokenizes string by delimiters. |262| **安全 / Safety** | ⚠️ 修改原字符串,非线程安全。多线程用 `strtok_r` |263264```c265char s[] = "one,two,three";266char *tok = strtok(s, ",");267while (tok) {268 printf("%s\n", tok);269 tok = strtok(NULL, ",");270}271```272273### strerror / 错误码转字符串 / Error Code to String274275| 项目 / Item | 内容 |276|---|---|277| **原型 / Prototype** | `char *strerror(int errnum);` |278| **说明 / Description** | 返回描述错误码的字符串。Returns string describing error code. |279| **安全 / Safety** | ⚠️ 非线程安全,多线程用 `strerror_r` |280281---282283## <stdlib.h> / <cstdlib> 通用工具 / General Utilities284285### malloc / 内存分配 / Memory Allocation286287| 项目 / Item | 内容 |288|---|---|289| **头文件 / Header** | `<stdlib.h>` / `<cstdlib>` |290| **原型 / Prototype** | `void *malloc(size_t size);` |291| **说明 / Description** | 分配 `size` 字节未初始化内存。Allocates `size` bytes of uninitialized memory. |292| **返回值 / Return** | 指针或 NULL(失败时) |293| **复杂度 / Complexity** | O(1) ~ O(n) 取决于实现 |294| **安全 / Safety** | ⚠️ 分配失败返回 NULL,需检查;不初始化内存 |295296```c297int *p = malloc(100 * sizeof(int));298if (!p) { /* 处理错误 */ }299free(p); p = NULL;300```301302### calloc / 分配并清零 / Allocate and Zero303304| 项目 / Item | 内容 |305|---|---|306| **原型 / Prototype** | `void *calloc(size_t nmemb, size_t size);` |307| **说明 / Description** | 分配 `nmemb * size` 字节并初始化为零。Allocates and zero-initializes. |308309```c310int *arr = calloc(100, sizeof(int)); // 100 个 int,全零311```312313### realloc / 重新分配 / Reallocate314315| 项目 / Item | 内容 |316|---|---|317| **原型 / Prototype** | `void *realloc(void *ptr, size_t size);` |318| **说明 / Description** | 调整已分配内存块大小。保留原数据(min(old, new) 字节)。Resizes memory block, preserves data. |319| **安全 / Safety** | ⚠️ 失败返回 NULL 但原指针仍有效,应使用临时变量接收 |320321```c322int *tmp = realloc(p, 200 * sizeof(int));323if (tmp) p = tmp;324else { /* 保留 p,处理错误 */ }325```326327### free / 释放内存 / Free Memory328329| 项目 / Item | 内容 |330|---|---|331| **原型 / Prototype** | `void free(void *ptr);` |332| **说明 / Description** | 释放 `malloc`/`calloc`/`realloc` 分配的内存。Frees allocated memory. |333| **安全 / Safety** | ⚠️ 不可释放栈内存、已释放内存(double free)、NULL 可安全释放 |334335### atoi / 字符串转整数 / String to Integer336337| 项目 / Item | 内容 |338|---|---|339| **原型 / Prototype** | `int atoi(const char *str);` |340| **说明 / Description** | 将字符串转为 int。转换失败行为未定义。Converts string to int. |341| **安全 / Safety** | ⚠️ 无错误检测,推荐 `strtol` |342343### strtol / 字符串转长整数 / String to Long344345| 项目 / Item | 内容 |346|---|---|347| **原型 / Prototype** | `long strtol(const char *str, char **endptr, int base);` |348| **说明 / Description** | 将字符串转为 long,支持指定进制和错误检测。Converts with base and error detection. |349| **参数 / Parameters** | `str` - 字符串; `endptr` - 存储第一个未转换字符的位置(可 NULL); `base` - 进制(0=自动检测, 8/10/16) |350| **返回值 / Return** | 转换结果,溢出时为 LONG_MAX/MIN 并设 errno |351352```c353char *end;354long val = strtol("123abc", &end, 10); // val=123, end 指向 "abc"355```356357### strtoul / 字符串转无符号长整数 / String to Unsigned Long358359| 项目 / Item | 内容 |360|---|---|361| **原型 / Prototype** | `unsigned long strtoul(const char *str, char **endptr, int base);` |362363### strtod / 字符串转双精度浮点 / String to Double364365| 项目 / Item | 内容 |366|---|---|367| **原型 / Prototype** | `double strtod(const char *str, char **endptr);` |368369### strtof / 字符串转浮点 / String to Float370371| 项目 / Item | 内容 |372|---|---|373| **原型 / Prototype** | `float strtof(const char *str, char **endptr);` |374375### rand / 随机数 / Random Number376377| 项目 / Item | 内容 |378|---|---|379| **原型 / Prototype** | `int rand(void);` |380| **说明 / Description** | 返回 [0, RAND_MAX] 伪随机整数。Returns pseudo-random integer in [0, RAND_MAX]. |381| **安全 / Safety** | ⚠️ 质量低,不适用于密码学。现代替代:arc4random 或 <random> |382383### srand / 设置随机种子 / Seed Random Generator384385| 项目 / Item | 内容 |386|---|---|387| **原型 / Prototype** | `void srand(unsigned int seed);` |388| **说明 / Description** | 设置 rand 的种子。通常 `srand(time(NULL))`。 |389390### arc4random / 安全随机数 / Secure Random (BSD)391392| 项目 / Item | 内容 |393|---|---|394| **头文件 / Header** | `<stdlib.h>` (BSD / macOS) |395| **原型 / Prototype** | `uint32_t arc4random(void);` |396| **说明 / Description** | 返回 [0, 2^32-1] 伪随机数,无需手动播种。Returns pseudo-random uint32, auto-seeded. |397398### qsort / 快速排序 / Quick Sort399400| 项目 / Item | 内容 |401|---|---|402| **原型 / Prototype** | `void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));` |403| **说明 / Description** | 对数组排序。Sorts array using comparison function. |404| **参数 / Parameters** | `base` - 数组起始; `nmemb` - 元素数; `size` - 元素大小; `compar` - 比较函数(返回 <0/0/>0) |405| **复杂度 / Complexity** | O(n log n) 平均 |406407```c408int cmp(const void *a, const void *b) {409 return (*(int*)a - *(int*)b);410}411int arr[] = {3, 1, 4, 1, 5};412qsort(arr, 5, sizeof(int), cmp);413```414415### bsearch / 二分搜索 / Binary Search416417| 项目 / Item | 内容 |418|---|---|419| **原型 / Prototype** | `void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));` |420| **说明 / Description** | 在已排序数组中二分查找。Binary search in sorted array. |421| **返回值 / Return** | 匹配元素的指针,未找到返回 NULL |422| **复杂度 / Complexity** | O(log n) |423| **前提 / Requirement** | 数组必须已排序 / Array must be sorted |424425### abs / labs / llabs / 绝对值 / Absolute Value426427| 项目 / Item | 内容 |428|---|---|429| **原型 / Prototype** | `int abs(int j);` / `long labs(long j);` / `long long llabs(long long j);` |430| **说明 / Description** | 返回绝对值。Returns absolute value. |431| **安全 / Safety** | ⚠️ `abs(INT_MIN)` 结果未定义(溢出) |432433### div / ldiv / 整数除法 / Integer Division434435| 项目 / Item | 内容 |436|---|---|437| **原型 / Prototype** | `div_t div(int numer, int denom);` / `ldiv_t ldiv(long numer, long denom);` |438| **说明 / Description** | 同时计算商和余数。Computes quotient and remainder. |439| **返回值 / Return** | `div_t { quot, rem }` 结构体 |440441### exit / 程序退出 / Program Exit442443| 项目 / Item | 内容 |444|---|---|445| **原型 / Prototype** | `void exit(int status);` / `_Exit(int status);` |446| **说明 / Description** | 正常终止程序,调用 atexit 注册的函数并刷新缓冲区。`_Exit` 不调用清理函数。 |447448### abort / 异常终止 / Abnormal Termination449450| 项目 / Item | 内容 |451|---|---|452| **原型 / Prototype** | `void abort(void);` |453| **说明 / Description** | 异常终止程序,生成 core dump。Abnormal termination, raises SIGABRT. |454455### atexit / 退出注册 / Exit Registration456457| 项目 / Item | 内容 |458|---|---|459| **原型 / Prototype** | `int atexit(void (*func)(void));` |460| **说明 / Description** | 注册程序正常退出时调用的函数。Registers function to be called on normal exit. |461462### system / 执行系统命令 / Execute System Command463464| 项目 / Item | 内容 |465|---|---|466| **原型 / Prototype** | `int system(const char *command);` |467| **说明 / Description** | 执行 shell 命令。Executes shell command. |468| **安全 / Safety** | ⚠️ 命令注入风险,避免拼接用户输入 |469470### getenv / 获取环境变量 / Get Environment Variable471472| 项目 / Item | 内容 |473|---|---|474| **原型 / Prototype** | `char *getenv(const char *name);` |475| **说明 / Description** | 获取环境变量值。返回的指针不应被修改或释放。Returns environment variable value. |476| **返回值 / Return** | 环境变量值的指针,不存在返回 NULL |477478---479480## <stdio.h> / <cstdio> 输入输出 / Input/Output481482### printf / 格式化输出 / Formatted Output483484| 项目 / Item | 内容 |485|---|---|486| **头文件 / Header** | `<stdio.h>` / `<cstdio>` |487| **原型 / Prototype** | `int printf(const char *format, ...);` |488| **说明 / Description** | 格式化输出到 stdout。Writes formatted output to stdout. |489| **返回值 / Return** | 输出的字符数,出错返回负数 |490| **常用格式 / Common Formats** | `%d` int, `%ld` long, `%lld` long long, `%u` unsigned, `%f` double, `%.2f` 保留2位, `%e` 科学计数, `%x` 十六进制, `%o` 八进制, `%s` 字符串, `%c` 字符, `%p` 指针, `%%` 百分号, `%zu` size_t |491492```c493printf("Name: %s, Age: %d, PI: %.2f\n", "Alice", 30, 3.14159);494```495496### fprintf / 文件格式化输出 / File Formatted Output497498| 项目 / Item | 内容 |499|---|---|500| **原型 / Prototype** | `int fprintf(FILE *stream, const char *format, ...);` |501| **说明 / Description** | 格式化输出到文件流。Writes formatted output to stream. |502503### sprintf / 字符串格式化 / String Format504505| 项目 / Item | 内容 |506|---|---|507| **原型 / Prototype** | `int sprintf(char *str, const char *format, ...);` |508| **说明 / Description** | 格式化输出到字符串。Writes formatted output to string buffer. |509| **安全 / Safety** | ⚠️ 缓冲区溢出风险,推荐 `snprintf` |510511### snprintf / 安全字符串格式化 / Safe String Format512513| 项目 / Item | 内容 |514|---|---|515| **原型 / Prototype** | `int snprintf(char *str, size_t size, const char *format, ...);` |516| **说明 / Description** | 最多写入 `size-1` 字节,始终 `\0` 结尾。返回需要的总长度。Writes up to `size-1` bytes, always null-terminated. |517| **安全 / Safety** | ✅ 安全 |518519```c520char buf[32];521int needed = snprintf(buf, sizeof(buf), "value=%d", 42);522if (needed >= sizeof(buf)) { /* 被截断 */ }523```524525### scanf / 格式化输入 / Formatted Input526527| 项目 / Item | 内容 |528|---|---|529| **原型 / Prototype** | `int scanf(const char *format, ...);` |530| **说明 / Description** | 从 stdin 格式化读取。Reads formatted input from stdin. |531| **返回值 / Return** | 成功匹配的项数 |532| **安全 / Safety** | ⚠️ 缓冲区溢出风险,建议用宽度限定符 `%99s` |533534```c535int n;536scanf("%d", &n);537char name[100];538scanf("%99s", name); // 限制宽度539```540541### fopen / 打开文件 / Open File542543| 项目 / Item | 内容 |544|---|---|545| **原型 / Prototype** | `FILE *fopen(const char *pathname, const char *mode);` |546| **说明 / Description** | 打开文件。Opens a file. |547| **模式 / Modes** | `"r"` 读, `"w"` 写(截断), `"a"` 追加, `"r+"` 读+写, `"w+"` 写+读(截断), `"a+"` 追加+读, `"rb"`/`"wb"` 二进制模式 |548| **返回值 / Return** | FILE 指针,失败返回 NULL |549550```c551FILE *f = fopen("data.txt", "r");552if (!f) { perror("fopen"); return 1; }553```554555### fclose / 关闭文件 / Close File556557| 项目 / Item | 内容 |558|---|---|559| **原型 / Prototype** | `int fclose(FILE *stream);` |560| **说明 / Description** | 关闭文件流,刷新缓冲区。Closes file stream, flushes buffers. |561562### fread / 读取数据块 / Read Block563564| 项目 / Item | 内容 |565|---|---|566| **原型 / Prototype** | `size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);` |567| **说明 / Description** | 从文件读取 `nmemb` 个大小为 `size` 的元素。Reads array of elements from file. |568| **返回值 / Return** | 实际读取的元素数 |569570```c571int arr[10];572size_t n = fread(arr, sizeof(int), 10, f);573```574575### fwrite / 写入数据块 / Write Block576577| 项目 / Item | 内容 |578|---|---|579| **原型 / Prototype** | `size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);` |580| **说明 / Description** | 向文件写入 `nmemb` 个大小为 `size` 的元素。Writes array of elements to file. |581582### fseek / 文件定位 / File Seek583584| 项目 / Item | 内容 |585|---|---|586| **原型 / Prototype** | `int fseek(FILE *stream, long offset, int whence);` |587| **说明 / Description** | 设置文件位置。Sets file position. |588| **whence** | `SEEK_SET` 文件开头, `SEEK_CUR` 当前位置, `SEEK_END` 文件末尾 |589590### ftell / 获取文件位置 / Get File Position591592| 项目 / Item | 内容 |593|---|---|594| **原型 / Prototype** | `long ftell(FILE *stream);` |595| **说明 / Description** | 返回当前文件位置。Returns current file position. |596597### rewind / 重置文件位置 / Rewind File598599| 项目 / Item | 内容 |600|---|---|601| **原型 / Prototype** | `void rewind(FILE *stream);` |602| **说明 / Description** | 等价于 `fseek(stream, 0, SEEK_SET); clearerr(stream);` |603604### fflush / 刷新缓冲区 / Flush Buffer605606| 项目 / Item | 内容 |607|---|---|608| **原型 / Prototype** | `int fflush(FILE *stream);` |609| **说明 / Description** | 刷新输出缓冲区。Flushing stdout for output. `fflush(NULL)` 刷新所有流。 |610611### fgets / 读取一行 / Read Line612613| 项目 / Item | 内容 |614|---|---|615| **原型 / Prototype** | `char *fgets(char *s, int size, FILE *stream);` |616| **说明 / Description** | 最多读取 `size-1` 个字符,包含 `\n`,始终 `\0` 结尾。Reads at most `size-1` chars including newline. |617| **返回值 / Return** | 成功返回 `s`,EOF 或错误返回 NULL |618| **安全 / Safety** | ✅ 安全 |619620```c621char line[256];622while (fgets(line, sizeof(line), f)) {623 printf("%s", line);624}625```626627### fputs / 写入字符串 / Write String628629| 项目 / Item | 内容 |630|---|---|631| **原型 / Prototype** | `int fputs(const char *s, FILE *stream);` |632| **说明 / Description** | 写入字符串到文件(不追加 `\n`)。Writes string to stream. |633634### fgetc / 读取单个字符 / Read Single Character635636| 项目 / Item | 内容 |637|---|---|638| **原型 / Prototype** | `int fgetc(FILE *stream);` |639| **说明 / Description** | 读取下一个字符。返回 int 以区分 EOF。Reads next character as int. |640| **返回值 / Return** | 字符(unsigned char 转为 int),EOF 表示结束或错误 |641642### fputc / 写入单个字符 / Write Single Character643644| 项目 / Item | 内容 |645|---|---|646| **原型 / Prototype** | `int fputc(int c, FILE *stream);` |647| **说明 / Description** | 写入一个字符到文件。Writes a character to stream. |648649### ungetc / 回退字符 / Push Back Character650651| 项目 / Item | 内容 |652|---|---|653| **原型 / Prototype** | `int ungetc(int c, FILE *stream);` |654| **说明 / Description** | 将字符推回流,下次读取会先读到它。Pushes character back to stream. |655656### feof / 检测文件结束 / Check End of File657658| 项目 / Item | 内容 |659|---|---|660| **原型 / Prototype** | `int feof(FILE *stream);` |661| **说明 / Description** | 检测是否到达文件末尾。Returns true if EOF flag is set. |662663### ferror / 检测错误 / Check Error664665| 项目 / Item | 内容 |666|---|---|667| **原型 / Prototype** | `int ferror(FILE *stream);` |668| **说明 / Description** | 检测是否发生错误。Returns true if error flag is set. |669670### remove / 删除文件 / Remove File671672| 项目 / Item | 内容 |673|---|---|674| **原型 / Prototype** | `int remove(const char *pathname);` |675| **说明 / Description** | 删除文件或空目录。Deletes file or empty directory. |676677### rename / 重命名 / Rename File678679| 项目 / Item | 内容 |680|---|---|681| **原型 / Prototype** | `int rename(const char *oldpath, const char *newpath);` |682| **说明 / Description** | 重命名或移动文件。Renames or moves a file. |683684### popen / 管道打开 / Pipe Open685686| 项目 / Item | 内容 |687|---|---|688| **原型 / Prototype** | `FILE *popen(const char *command, const char *type);` |689| **说明 / Description** | 创建管道并执行命令。Creates pipe to/from command. |690| **type** | `"r"` 读取命令输出, `"w"` 写入命令输入 |691692```c693FILE *fp = popen("ls -la", "r");694char line[256];695while (fgets(line, sizeof(line), fp)) puts(line);696pclose(fp);697```698699---700701## <math.h> / <cmath> 数学 / Mathematics702703### fabs / 绝对值(浮点)/ Absolute Value (Float)704705| 项目 / Item | 内容 |706|---|---|707| **头文件 / Header** | `<math.h>` / `<cmath>` |708| **原型 / Prototype** | `double fabs(double x);` / `float fabsf(float);` / `long double fabsl(long double);` |709| **说明 / Description** | 返回浮点绝对值。Returns floating-point absolute value. |710711### fmod / 浮点取模 / Float Modulo712713| 项目 / Item | 内容 |714|---|---|715| **原型 / Prototype** | `double fmod(double x, double y);` |716| **说明 / Description** | 返回 x/y 的浮点余数。Returns floating-point remainder of x/y. |717718### floor / ceil / trunc / round / 取整函数 / Rounding Functions719720| 项目 / Item | 内容 |721|---|---|722| **原型 / Prototype** | `double floor(double x);` `double ceil(double x);` `double trunc(double x);` `double round(double x);` |723| **说明 / Description** | `floor` 向下取整 / round down; `ceil` 向上取整 / round up; `trunc` 向零取整 / toward zero; `round` 四舍五入 / round to nearest |724725```c726floor(3.7) // 3.0727ceil(3.2) // 4.0728trunc(-3.7) // -3.0729round(3.5) // 4.0730```731732### sqrt / 平方根 / Square Root733734| 项目 / Item | 内容 |735|---|---|736| **原型 / Prototype** | `double sqrt(double x);` |737| **说明 / Description** | 返回非负平方根。Returns non-negative square root. |738| **注意 / Note** | 负数返回 NaN |739740### pow / 幂运算 / Power741742| 项目 / Item | 内容 |743|---|---|744| **原型 / Prototype** | `double pow(double base, double exponent);` |745| **说明 / Description** | 返回 base^exponent。Returns base raised to exponent. |746747### exp / log / log2 / log10 / 指数与对数 / Exponential and Logarithm748749| 项目 / Item | 内容 |750|---|---|751| **原型 / Prototype** | `double exp(double x);` `double log(double x);` `double log2(double x);` `double log10(double x);` |752| **说明 / Description** | `exp` e^x; `log` 自然对数 ln(x); `log2` log₂(x); `log10` log₁₀(x) |753754### sin / cos / tan / 三角函数 / Trigonometric Functions755756| 项目 / Item | 内容 |757|---|---|758| **原型 / Prototype** | `double sin(double x);` `double cos(double x);` `double tan(double x);` |759| **说明 / Description** | 参数为弧度。Arguments in radians. |760761### asin / acos / atan / atan2 / 反三角函数 / Inverse Trigonometric762763| 项目 / Item | 内容 |764|---|---|765| **原型 / Prototype** | `double asin(double x);` `double acos(double x);` `double atan(double y, double x);` |766| **说明 / Description** | `asin` [-1,1]→[-π/2,π/2]; `acos` [-1,1]→[0,π]; `atan2`(y,x) 返回 atan(y/x) 并正确处理象限 |767768### isnan / isinf / isfinite / 浮点分类 / Float Classification769770| 项目 / Item | 内容 |771|---|---|772| **头文件 / Header** | `<math.h>` (C99) |773| **原型 / Prototype** | `int isnan(double x);` `int isinf(double x);` `int isfinite(double x);` |774| **说明 / Description** | 检测 NaN、无穷大、有限值。Detects NaN, infinity, finite values. |775776### copysign / 复制符号 / Copy Sign777778| 项目 / Item | 内容 |779|---|---|780| **原型 / Prototype** | `double copysign(double x, double y);` |781| **说明 / Description** | 返回 x 的绝对值与 y 的符号组合。Returns magnitude of x with sign of y. |782783### 数学常量 / Math Constants784785| 常量 / Constant | 值 / Value | 说明 |786|---|---|---|787| `M_PI` | 3.14159265358979323846 | π |788| `M_E` | 2.71828182845904523536 | e |789| `HUGE_VAL` | double 正无穷 | 正无穷大 |790| `INFINITY` | float/double 正无穷 | 正无穷大 |791| `NAN` | NaN | 非数值 |792793---794795## <ctype.h> / <cctype> 字符分类 / Character Classification796797| 函数 / Function | 说明 / Description | 示例 |798|---|---|---|799| `int isdigit(int c)` | 数字 0-9 / decimal digit | `isdigit('5')` → true |800| `int isxdigit(int c)` | 十六进制数字 0-9,a-f,A-F / hex digit | `isxdigit('A')` → true |801| `int isalpha(int c)` | 字母 a-z,A-Z / alphabetic | `isalpha('K')` → true |802| `int isalnum(int c)` | 字母或数字 / alphanumeric | `isalnum('3')` → true |803| `int isspace(int c)` | 空白字符 / whitespace | `isspace(' ')` → true |804| `int isupper(int c)` | 大写字母 / uppercase | `isupper('A')` → true |805| `int islower(int c)` | 小写字母 / lowercase | `islower('a')` → true |806| `int isprint(int c)` | 可打印字符 / printable | `isprint('!')` → true |807| `int ispunct(int c)` | 标点符号 / punctuation | `ispunct(',')` → true |808| `int iscntrl(int c)` | 控制字符 / control | `iscntrl('\n')` → true |809| `int isgraph(int c)` | 图形字符(可打印且非空格)/ graphic | `isgraph('A')` → true |810| `int toupper(int c)` | 转大写 / to uppercase | `toupper('a')` → 'A' |811| `int tolower(int c)` | 转小写 / to lowercase | `tolower('A')` → 'a' |812813**注意 / Note:** 参数应为 unsigned char 或 EOF。传入负值 char(如中文)是未定义行为。814815---816817## <time.h> / <ctime> 时间 / Time818819### time / 获取当前时间 / Get Current Time820821| 项目 / Item | 内容 |822|---|---|823| **头文件 / Header** | `<time.h>` / `<ctime>` |824| **原型 / Prototype** | `time_t time(time_t *tloc);` |825| **说明 / Description** | 返回当前日历时间(秒数,自 Epoch 1970-01-01)。Returns current calendar time. |826827### localtime / 本地时间分解 / Local Time Decomposition828829| 项目 / Item | 内容 |830|---|---|831| **原型 / Prototype** | `struct tm *localtime(const time_t *timep);` |832| **说明 / Description** | 将 time_t 转为本地时间的 struct tm。Converts to local time broken-down form. |833| **安全 / Safety** | ⚠️ 返回静态缓冲区,非线程安全。多线程用 `localtime_r` |834835### gmtime / UTC 时间分解 / UTC Time Decomposition836837| 项目 / Item | 内容 |838|---|---|839| **原型 / Prototype** | `struct tm *gmtime(const time_t *timep);` |840| **说明 / Description** | 转为 UTC 时间的 struct tm。Converts to UTC time. |841842### mktime / 时间合成 / Make Time843844| 项目 / Item | 内容 |845|---|---|846| **原型 / Prototype** | `time_t mktime(struct tm *tm);` |847| **说明 / Description** | 将 struct tm 转为 time_t。Converts broken-down time to time_t. |848849### strftime / 时间格式化 / Format Time850851| 项目 / Item | 内容 |852|---|---|853| **原型 / Prototype** | `size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);` |854| **常用格式 / Formats** | `%Y` 年(4位), `%m` 月(01-12), `%d` 日(01-31), `%H` 时(00-23), `%M` 分, `%S` 秒, `%F` `%Y-%m-%d`, `%T` `%H:%M:%S`, `%c` 本地日期时间 |855856```c857time_t now = time(NULL);858struct tm *t = localtime(&now);859char buf[64];860strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);861printf("%s\n", buf); // 2024-01-15 14:30:00862```863864### clock / 进程 CPU 时间 / Process CPU Time865866| 项目 / Item | 内容 |867|---|---|868| **原型 / Prototype** | `clock_t clock(void);` |869| **说明 / Description** | 返回进程使用的 CPU 时间。Returns CPU time used. |870| **常量** | `CLOCKS_PER_SEC` 每秒时钟数 |871872```c873clock_t start = clock();874// ... 工作 ...875double elapsed = (double)(clock() - start) / CLOCKS_PER_SEC;876```877878### struct tm / 分解时间结构 / Broken-down Time Structure879880```c881struct tm {882 int tm_sec; // 秒 [0,60]883 int tm_min; // 分 [0,59]884 int tm_hour; // 时 [0,23]885 int tm_mday; // 日 [1,31]886 int tm_mon; // 月 [0,11] ⚠️ 从0开始887 int tm_year; // 年-1900888 int tm_wday; // 星期 [0,6] 0=周日889 int tm_yday; // 一年中的第几天 [0,365]890 int tm_isdst; // 夏令时标志891};892```893894---895896## <signal.h> / <csignal> 信号 / Signals897898| 函数 / Function | 说明 / Description |899|---|---|900| `void (*signal(int sig, void (*handler)(int)))(int);` | 设置信号处理函数 / Set signal handler |901| `int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact);` | POSIX 信号处理(推荐)/ POSIX signal handling (recommended) |902| `int kill(pid_t pid, int sig);` | 向进程发送信号 / Send signal to process |903| `int raise(int sig);` | 向自身发送信号 / Send signal to self |904| `unsigned int alarm(unsigned int seconds);` | 设置定时 SIGALRM / Schedule SIGALRM |905906### 常用信号 / Common Signals907908| 信号 / Signal | 值 / Value | 说明 / Description |909|---|---|---|910| `SIGINT` | 2 | 中断 (Ctrl+C) / Interrupt |911| `SIGTERM` | 15 | 终止请求 / Termination |912| `SIGKILL` | 9 | 强制终止(不可捕获)/ Kill (uncatchable) |913| `SIGSEGV` | 11 | 段错误 / Segmentation fault |914| `SIGPIPE` | 13 | 管道破裂(写已关闭的管道)/ Broken pipe |915| `SIGCHLD` | 20 | 子进程状态变化 / Child status change |916| `SIGALRM` | 14 | 定时器到期 / Alarm clock |917918```c919#include <signal.h>920#include <stdio.h>921#include <unistd.h>922923volatile sig_atomic_t running = 1;924void handler(int sig) { running = 0; }925926int main() {927 signal(SIGINT, handler);928 while (running) { pause(); }929 printf("退出\n");930}931```932933---934935## <assert.h> / <cassert> 断言 / Assertions936937| 项目 / Item | 内容 |938|---|---|939| **头文件 / Header** | `<assert.h>` / `<cassert>` |940| **宏 / Macro** | `void assert(scalar expression);` |941| **说明 / Description** | 表达式为 0 时打印诊断信息并调用 `abort()`。Aborts if expression is false. |942| **禁用 / Disable** | 定义 `NDEBUG` 宏可禁用所有 assert。`#define NDEBUG` before include disables all asserts. |943944```c945#include <assert.h>946void process(int *p) {947 assert(p != NULL); // p 为 NULL 时终止948 // ...949}950```951952---953954## <errno.h> / <cerrno> 错误码 / Error Codes955956| 项目 / Item | 内容 |957|---|---|958| **头文件 / Header** | `<errno.h>` / `<cerrno>` |959| **变量 / Variable** | `int errno;` — 由库函数设置的全局错误码 |960| **函数** | `void perror(const char *s);` — 打印 errno 对应的错误信息到 stderr |961| **函数** | `char *strerror(int errnum);` — 返回错误描述字符串 |962963### 常见错误码 / Common Error Codes964965| 错误码 / Code | 值 / Value | 说明 / Description |966|---|---|---|967| `EINVAL` | 22 | 无效参数 / Invalid argument |968| `ENOMEM` | 12 | 内存不足 / Out of memory |969| `ENOENT` | 2 | 文件或目录不存在 / No such file |970| `EACCES` | 13 | 权限不足 / Permission denied |971| `EINTR` | 4 | 被信号中断 / Interrupted system call |972| `EAGAIN` / `EWOULDBLOCK` | 35 / 11 | 资源暂时不可用 / Resource temporarily unavailable |973| `EPERM` | 1 | 操作不允许 / Operation not permitted |974975```c976#include <errno.h>977FILE *f = fopen("nonexistent.txt", "r");978if (!f) {979 perror("fopen"); // fopen: No such file or directory980 printf("errno=%d\n", errno); // errno=2981}982```983984---985986## <stdint.h> / <cstdint> 定宽整数 / Fixed-Width Integers987988| 类型 / Type | 说明 / Description |989|---|---|990| `int8_t` ~ `int64_t` | 有符号 8/16/32/64 位整数 / Signed fixed-width |991| `uint8_t` ~ `uint64_t` | 无符号 8/16/32/64 位整数 / Unsigned fixed-width |992| `intptr_t` / `uintptr_t` | 可容纳指针的整数 / Integer type holding a pointer |993| `size_t` | sizeof 返回的无符号类型 / Unsigned type from sizeof |994| `ptrdiff_t` | 指针差值的有符号类型 / Signed pointer difference |995| `intmax_t` / `uintmax_t` | 最大宽度整数 / Maximum width integer |996997### 极限宏 / Limit Macros998999| 宏 / Macro | 说明 / Description |1000|---|---|1001| `INT8_MIN` / `INT8_MAX` | int8_t 最小/最大值 |1002| `INT64_MIN` / `INT64_MAX` | int64_t 范围: -2^63 ~ 2^63-1 |1003| `UINT64_MAX` | 2^64 - 1 = 18446744073709551615 |1004| `SIZE_MAX` | size_t 最大值 |10051006---10071008## <stddef.h> / <cstddef> 标准定义 / Standard Definitions10091010| 项目 / Item | 内容 |1011|---|---|1012| `size_t` | sizeof 运算符结果的无符号整数类型 |1013| `ptrdiff_t` | 两个指针差值的有符号整数类型 |1014| `offsetof(type, member)` | 结构体成员偏移量(字节) |1015| `NULL` | 空指针常量 |1016| `max_align_t` | 最大对齐要求的类型 |10171018---10191020## <stdbool.h> / <cstdbool> 布尔 / Boolean10211022| 项目 / Item | 内容 |1023|---|---|1024| `bool` | 布尔类型(展开为 `_Bool`) |1025| `true` | 展开为 `1` |1026| `false` | 展开为 `0` |1027| `__bool_true_false_are_defined` | 展开为 `1` |10281029> C++ 中 `bool`/`true`/`false` 是内置关键字,无需此头文件。10301031---10321033## <inttypes.h> / <cinttypes> 格式化宏 / Formatting Macros10341035用于 `printf`/`scanf` 打印 `int64_t` 等定宽类型。10361037| 宏 / Macro | 用途 / Usage | 示例 |1038|---|---|---|1039| `PRId64` | printf int64_t | `printf("%" PRId64, val);` |1040| `PRIu64` | printf uint64_t | `printf("%" PRIu64, val);` |1041| `PRIX64` | printf uint64_t 十六进制大写 | `printf("%" PRIX64, val);` |1042| `SCNd64` | scanf int64_t | `scanf("%" SCNd64, &val);` |10431044---10451046## <limits.h> / <climits> 极限值 / Limits10471048| 宏 / Macro | 说明 / Description |1049|---|---|1050| `CHAR_BIT` | char 的位数(通常 8) |1051| `INT_MIN` / `INT_MAX` | int 范围: -32768 ~ 32767 (16位) 或 -2^31 ~ 2^31-1 (32位) |1052| `LONG_MAX` | long 最大值 |1053| `LLONG_MAX` | long long 最大值: 2^63-1 |1054| `MB_LEN_MAX` | 多字节字符最大字节数 |1055| `UCHAR_MAX` | unsigned char 最大值: 255 |1056| `USHRT_MAX` | unsigned short 最大值: 65535 |1057| `UINT_MAX` | unsigned int 最大值 |1058| `ULONG_MAX` | unsigned long 最大值 |10591060---10611062## <float.h> / <cfloat> 浮点极限 / Floating-Point Limits10631064| 宏 / Macro | 说明 / Description |1065|---|---|1066| `FLT_MIN` / `FLT_MAX` | float 最小/最大正规值 |1067| `DBL_MIN` / `DBL_MAX` | double 最小/最大正规值 |1068| `FLT_EPSILON` | float 最小可表示差值(≈1.19e-7) |1069| `DBL_EPSILON` | double 最小可表示差值(≈2.22e-16) |1070| `LDBL_DIG` | long double 十进制精度位数 |1071| `FLT_DIG` / `DBL_DIG` | 十进制精度位数(6 / 15) |1072| `DECIMAL_DIG` | 最宽类型十进制精度 |10731074---10751076# C++ 标准库 (C++ Standard Library / C++ 标准库)10771078---10791080## <string> 字符串 / Strings10811082### std::string 构造与基本操作 / Construction & Basics10831084| 操作 / Operation | 说明 / Description | 示例 |1085|---|---|---|1086| `string s;` | 默认构造,空字符串 | |1087| `string s("hello");` | C 字符串构造 | |1088| `string s(5, 'a');` | 5 个 'a' → "aaaaa" | |1089| `string s2 = s;` | 拷贝构造 | |1090| `string s3 = std::move(s);` | 移动构造 / Move construct | |1091| `s = "world";` | 赋值 / Assign | |1092| `s.empty()` | 是否为空 / Is empty | `s.empty()` → false |1093| `s.size()` / `s.length()` | 字符数 / Character count | |1094| `s.capacity()` | 已分配容量 / Allocated capacity | |1095| `s.reserve(100)` | 预留容量(不改变 size)/ Reserve capacity | |1096| `s.shrink_to_fit()` | 释放多余容量 / Release excess capacity (C++11) | |1097| `s.c_str()` | 返回 C 字符串(const char*) | |1098| `s.data()` | 返回可修改的字符数组指针 (C++17) | |10991100### 连接与比较 / Concatenation & Comparison11011102| 操作 / Operation | 说明 / Description |1103|---|---|1104| `s1 + s2` | 连接 / Concatenation |1105| `s += "x"` | 追加 / Append |1106| `s.append("xyz")` | 追加字符串 |1107| `s.push_back('a')` | 追加单个字符 |1108| `s1 == s2` / `s1 != s2` | 相等比较 / Equality |1109| `s1 < s2` / `s1 > s2` | 字典序比较 / Lexicographic |1110| `s1.compare(s2)` | 比较函数(<0/0/>0) |11111112### 查找 / Searching11131114| 操作 / Operation | 说明 / Description | 复杂度 |1115|---|---|---|1116| `s.find("ab")` | 查找子串首次出现位置 / First occurrence | O(n*m) |1117| `s.rfind("ab")` | 查找子串最后出现位置 / Last occurrence | O(n*m) |1118| `s.find_first_of("aeiou")` | 查找任一字符首次出现 | O(n) |1119| `s.find_last_of("aeiou")` | 查找任一字符最后出现 | O(n) |1120| `s.find_first_not_of("abc")` | 查找不在集合中的首个字符 | O(n) |1121| `s.substr(pos, len)` | 提取子串 / Extract substring | O(n) |1122| **返回值** | `string::npos` 表示未找到 | |11231124### 修改 / Modification11251126| 操作 / Operation | 说明 / Description |1127|---|---|1128| `s.insert(pos, "str")` | 在 pos 插入 |1129| `s.erase(pos, len)` | 删除从 pos 开始的 len 个字符 |1130| `s.replace(pos, len, "new")` | 替换 |1131| `s.clear()` | 清空 |11321133### 字符串转换 / String Conversion (C++11)11341135| 函数 / Function | 说明 / Description |1136|---|---|1137| `std::stoi(s)` | 字符串→int |1138| `std::stol(s)` | 字符串→long |1139| `std::stoll(s)` | 字符串→long long |1140| `std::stoul(s)` | 字符串→unsigned long |1141| `std::stod(s)` | 字符串→double |1142| `std::stof(s)` | 字符串→float |1143| `std::to_string(42)` | 数值→string |11441145### std::string_view (C++17) / 字符串视图11461147| 项目 / Item | 内容 |1148|---|---|1149| **头文件 / Header** | `<string_view>` |1150| **说明 / Description** | 非拥有字符串视图,零拷贝引用字符串片段。Non-owning reference to string. |11511152| 操作 / Operation | 说明 / Description |1153|---|---|1154| `string_view sv("hello");` | 构造 |1155| `sv.substr(pos, len)` | 子串视图 / Sub-view |1156| `sv.starts_with("he")` | 前缀匹配 (C++20) |1157| `sv.ends_with("lo")` | 后缀匹配 (C++20) |1158| `sv.find("ll")` | 查找 |1159| `sv.compare(sv2)` | 比较 |1160| `sv.size()` / `sv.length()` | 长度 |1161| `sv.data()` | 底层数据指针 |1162| `sv.empty()` | 是否为空 |11631164```cpp1165void process(std::string_view sv) {1166 // 无拷贝地处理字符串片段1167 if (sv.starts_with("http")) { /* ... */ }1168}1169process("https://example.com");1170std::string s = "hello";1171process(s); // 隐式转换1172```11731174---11751176## <vector> 动态数组 / Dynamic Arrays11771178### 构造与基本操作 / Construction & Basics11791180| 操作 / Operation | 说明 / Description | 复杂度 |1181|---|---|---|1182| `vector<int> v;` | 默认构造,空 | O(1) |1183| `vector<int> v(100);` | 100 个默认值元素 | O(n) |1184| `vector<int> v(10, 42);` | 10 个值为 42 | O(n) |1185| `vector<int> v{1,2,3};` | 初始化列表 (C++11) | O(n) |1186| `vector<int> v2(v);` | 拷贝构造 | O(n) |1187| `vector<int> v3(std::move(v));` | 移动构造 | O(1) |11881189### 元素访问 / Element Access11901191| 操作 / Operation | 说明 / Description |1192|---|---|1193| `v[i]` | 下标访问(无边界检查)/ No bounds check |1194| `v.at(i)` | 带边界检查,越界抛 `out_of_range` / Bounds checked |1195| `v.front()` | 第一个元素 |1196| `v.back()` | 最后一个元素 |1197| `v.data()` | 底层数组指针 |1198| `v.size()` | 元素个数 |1199| `v.capacity()` | 已分配容量 |1200| `v.empty()` | 是否为空 |12011202### 修改 / Modification12031204| 操作 / Operation | 说明 / Description | 复杂度 | 迭代器失效 |1205|---|---|---|---|1206| `v.push_back(x)` | 末尾添加 | 均摊 O(1) | 可能全部失效 |1207| `v.emplace_back(args...)` | 原地构造末尾元素 (C++11) | 均摊 O(1) | 可能全部失效 |1208| `v.pop_back()` | 移除末尾元素 | O(1) | 仅 end() 失效 |1209| `v.insert(pos, x)` | 在 pos 处插入 | O(n) | pos 及之后失效 |1210| `v.erase(pos)` | 删除 pos 处元素 | O(n) | pos 及之后失效 |1211| `v.resize(n)` | 调整大小(新元素默认值) | O(n) | 可能全部失效 |1212| `v.reserve(n)` | 预留容量(不改变 size) | O(n) 最坏 | 不失效 |1213| `v.shrink_to_fit()` | 释放多余容量 (C++11) | O(n) | 不失效 |1214| `v.clear()` | 清空所有元素 | O(n) | 全部失效 |1215| `v.swap(v2)` | 交换内容 | O(1) | 引用其他容器失效 |12161217### 迭代器 / Iterators12181219| 操作 / Operation | 说明 / Description |1220|---|---|1221| `v.begin()` / `v.end()` | 正向迭代器 |1222| `v.rbegin()` / `v.rend()` | 反向迭代器 |1223| `v.cbegin()` / `v.cend()` | const 迭代器 |12241225### 迭代器失效规则 / Iterator Invalidation Rules12261227- `push_back` / `emplace_back`:若发生重分配(`size == capacity`),所有迭代器/指针/引用失效1228- `insert`:插入点及之后的所有失效1229- `erase`:删除点及之后的所有失效1230- `pop_back`:仅 `end()` 失效1231- `resize`:若增大则可能全部失效1232- `reserve` / `shrink_to_fit`:可能全部失效12331234### 二维 vector / 2D Vector12351236```cpp1237vector<vector<int>> matrix(3, vector<int>(4, 0)); // 3×4 全零1238matrix[1][2] = 42;1239for (auto& row : matrix) {1240 for (auto& val : row) {1241 cout << val << " ";1242 }1243 cout << "\n";1244}1245```12461247---12481249## <list> / <forward_list> 链表 / Linked Lists12501251| 操作 / Operation | list | forward_list | 说明 / Description |1252|---|---|---|---|1253| `push_back(x)` | ✅ | ❌ | 末尾添加 |1254| `push_front(x)` | ✅ | ✅ | 头部添加 O(1) |1255| `pop_back()` | ✅ | ❌ | 移除末尾 |1256| `pop_front()` | ✅ | ✅ | 移除头部 O(1) |1257| `insert(pos, x)` | ✅ | ✅ | 插入 O(1) |1258| `erase(pos)` | ✅ | ✅ | 删除 O(1) |1259| `splice(pos, other)` | ✅ | ✅ | 转移节点 O(1) |1260| `sort()` | ✅ | ✅ | 排序 O(n log n) |1261| `unique()` | ✅ | ✅ | 去除连续重复 O(n) |1262| `merge(other)` | ✅ | ✅ | 合并有序链表 O(n) |1263| `reverse()` | ✅ | ✅ | 反转 O(n) |1264| `remove(val)` | ✅ | ✅ | 移除所有等于 val 的元素 O(n) |12651266> 链表特点:任意位置插入/删除 O(1),不支持随机访问,缓存不友好。12671268---12691270## <deque> 双端队列 / Double-Ended Queue12711272| 操作 / Operation | 说明 / Description | 复杂度 |1273|---|---|---|1274| `push_front(x)` / `push_back(x)` | 头/尾添加 | O(1) |1275| `pop_front()` / `pop_back()` | 头/尾移除 | O(1) |1276| `d[i]` / `d.at(i)` | 随机访问 | O(1) |1277| `d.front()` / `d.back()` | 首/尾元素 | O(1) |1278| `d.insert(pos, x)` | 插入 | O(n) |1279| `d.size()` / `d.empty()` | 大小/判空 | O(1) |12801281> deque 内存为分段连续,支持 O(1) 首尾操作和随机访问。中间插入仍为 O(n)。12821283---12841285## <map> / <unordered_map> 关联容器 / Associative Containers12861287### std::map(有序映射)/ Ordered Map12881289| 操作 / Operation | 说明 / Description | 复杂度 |1290|---|---|---|1291| `m[key] = val` | 插入或更新(不存在时默认构造)/ Insert or update | O(log n) |1292| `m.at(key)` | 访问,不存在抛异常 / Access with bounds check | O(log n) |1293| `m.insert({key, val})` | 插入,返回 pair<iterator,bool> | O(log n) |1294| `m.emplace(key, val)` | 原地插入 (C++11) | O(log n) |1295| `m.erase(key)` | 按键删除 | O(log n) |1296| `m.erase(it)` | 按迭代器删除 | O(1) 均摊 |1297| `m.find(key)` | 查找,返回迭代器 | O(log n) |1298| `m.count12991300…(truncated)