C++常用函数库

梦想不会自己发光,真正闪耀的是那个为梦狂奔的你。献给知行的孩子们!(Eric.He著)


  本教程将全面讲解C++开发中高频使用的函数库,包括数学库cmath、算法库algorithm、通用工具库utility、字符串操作库cstring、字符判断库cctype、随机数库cstdlib、时间库ctime、输入输出库cstdio,帮助你掌握各类函数的核心用法和应用场景。

教程目录导航

一、数学库cmath

1.1 核心功能与常用函数

cmath是C++核心数学库,提供各类数学运算函数,需包含头文件 #include <cmath>,核心函数分类如下:

函数类别 函数名 功能说明
基本运算 abs(x) / fabs(x) 绝对值(abs用于整数,fabs用于浮点数)
pow(x, y) 计算x的y次方(x^y)
sqrt(x) 计算x的平方根
三角函数 sin(x) / cos(x) / tan(x) 正弦/余弦/正切(参数为弧度)
asin(x) / acos(x) / atan(x) 反正弦/反余弦/反正切
atan2(y, x) 计算y/x的反正切,返回弧度
指数/对数 exp(x) 自然指数e^x
log(x) / log10(x) 自然对数(lnx)/ 以10为底的对数(lgx)
取整函数 round(x) 四舍五入(如round(3.2)=3,round(3.8)=-4)
floor(x) 向下取整(如floor(3.8)=3,floor(-3.8)=-4)
ceil(x) 向上取整(如ceil(3.2)=4,ceil(-3.2)=-3)
最值函数 fmax(x,y) / fmin(x,y) 浮点数最大值/最小值

1.2 实战示例


#include <iostream>
#include <cmath>
using namespace std;

int main() {
    // 基本运算
    int a = -10;
    double b = 3.14, c = 2.0;
    cout << "a的绝对值:" << abs(a) << endl;
    cout << "b的平方根:" << sqrt(b) << endl;
    cout << "2的3次方:" << pow(2, 3) << endl;

    // 三角函数(弧度转角度:弧度*180/π)
    double rad = M_PI / 4; // π/4弧度 = 45度
    cout << "45度正弦值:" << sin(rad) << endl;
    cout << "45度余弦值:" << cos(rad) << endl;

    // 取整函数
    double d = 5.6, e = -2.3;
    cout << "floor(5.6) = " << floor(d) << endl; // 5
    cout << "ceil(-2.3) = " << ceil(e) << endl;   // -2

    // 最值函数
    cout << "fmax(3.5, 7.2) = " << fmax(3.5, 7.2) << endl; // 7.2
    cout << "fmin(3.5, 7.2) = " << fmin(3.5, 7.2) << endl; // 3.5

    return 0;
}
        

注意:M_PI是cmath中定义的圆周率常量(π),部分编译器需开启特定选项才能使用(如GCC需加-D_USE_MATH_DEFINES)。

二、算法库algorithm

2.1 取最大值/最小值函数

algorithm是C++算法标准库,提供通用算法实现,需包含头文件 #include <algorithm>,核心最值函数如下:

函数名 功能说明 语法示例
max(a, b) 返回a和b中的最大值(支持任意可比较类型) max(5, 9) → 9;max(3.2, 1.8) → 3.2
min(a, b) 返回a和b中的最小值 min(5, 9) → 5;min(3.2, 1.8) → 1.8
max_element(迭代器起始, 迭代器结束) 返回数组/容器中最大值的迭代器 max_element(arr, arr+5) → 指向最大值的指针
min_element(迭代器起始, 迭代器结束) 返回数组/容器中最小值的迭代器 min_element(arr, arr+5) → 指向最小值的指针

2.2 实战示例


#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    // 基础最值函数
    int x = 10, y = 20;
    double m = 5.5, n = 3.8;
    cout << "max(10,20) = " << max(x, y) << endl;       // 20
    cout << "min(5.5,3.8) = " << min(m, n) << endl;     // 3.8

    // 数组最值函数
    int arr[] = {3, 8, 1, 9, 5};
    int len = sizeof(arr) / sizeof(arr[0]);
    
    // max_element返回迭代器(指针),需解引用取值
    int maxVal = *max_element(arr, arr + len);
    int minVal = *min_element(arr, arr + len);
    cout << "数组最大值:" << maxVal << endl; // 9
    cout << "数组最小值:" << minVal << endl; // 1

    return 0;
}
        

三、通用工具库utility

3.1 值交换函数swap

utility库提供通用工具函数,swap是最常用的函数,用于交换两个变量的值,需包含头文件 #include <utility>(部分编译器中algorithm也包含swap)。

语法swap(a, b),直接交换a和b的内存值,支持任意类型(int、double、字符串、自定义类型等)。

3.2 实战示例


#include <iostream>
#include <utility>
#include <string>
using namespace std;

int main() {
    // 交换整数
    int a = 10, b = 20;
    cout << "交换前:a=" << a << ", b=" << b << endl;
    swap(a, b);
    cout << "交换后:a=" << a << ", b=" << b << endl; // a=20, b=10

    // 交换字符串
    string s1 = "hello", s2 = "world";
    cout << "\n交换前:s1=" << s1 << ", s2=" << s2 << endl;
    swap(s1, s2);
    cout << "交换后:s1=" << s1 << ", s2=" << s2 << endl; // s1=world, s2=hello

    // 交换浮点数
    double x = 3.14, y = 6.28;
    cout << "\n交换前:x=" << x << ", y=" << y << endl;
    swap(x, y);
    cout << "交换后:x=" << x << ", y=" << y << endl; // x=6.28, y=3.14

    return 0;
}
        

四、字符串操作库cstring

4.1 核心函数分类

cstring是C风格字符串操作库,针对char[]类型字符串,需包含头文件 #include <cstring>,核心函数如下:

函数类别 函数名 功能说明
长度计算 strlen(str) 返回字符串有效长度(不含末尾的'\0')
字符串拷贝 strcpy(dst, src) 将src字符串拷贝到dst(含'\0',需确保dst空间足够)
strncpy(dst, src, n) 拷贝src前n个字符到dst(更安全)
字符串拼接 strcat(dst, src) 将src拼接到dst末尾
strncat(dst, src, n) 将src前n个字符拼接到dst末尾
字符串比较 strcmp(s1, s2) 比较s1和s2:相等返回0,s1>s2返回正数,s1
字符查找 strchr(str, ch) 查找str中第一个ch字符,返回指针;无则返回NULL

4.2 实战示例


#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str1[50] = "Hello";
    char str2[20] = " World";
    
    // 长度计算
    cout << "str1长度:" << strlen(str1) << endl; // 5(不含'\0')
    cout << "str1数组大小:" << sizeof(str1) << endl; // 50

    // 字符串拼接
    strcat(str1, str2);
    cout << "拼接后str1:" << str1 << endl; // Hello World

    // 字符串拷贝
    char str3[50];
    strcpy(str3, str1);
    cout << "拷贝后str3:" << str3 << endl; // Hello World

    // 字符串比较
    char str4[] = "Hello";
    char str5[] = "Hello";
    char str6[] = "Hi";
    cout << "strcmp(str4, str5) = " << strcmp(str4, str5) << endl; // 0(相等)
    cout << "strcmp(str4, str6) = " << strcmp(str4, str6) << endl; // 负数(Hello < Hi)

    // 字符查找
    char* pos = strchr(str1, 'W');
    if (pos != NULL) {
        cout << "找到'W',位置:" << pos - str1 << endl; // 6(索引从0开始)
    }

    return 0;
}
        

注意:使用strcpy/strcat时,目标数组必须有足够空间,否则会导致内存越界;优先使用strncpy/strncat提升安全性。

五、字符判断库cctype

5.1 字符判断/转换函数

cctype库提供字符类型判断和转换函数,需包含头文件 #include <cctype>,核心函数如下:

函数类别 函数名 功能说明
字符类型判断 isalpha(ch) 判断是否为字母(a-z/A-Z),是返回非0,否返回0
isdigit(ch) 判断是否为数字(0-9)
isspace(ch) 判断是否为空白字符(空格、换行、制表符等)
字符大小写转换 toupper(ch) 将小写字母转为大写,非小写字母返回原值
tolower(ch) 将大写字母转为小写,非大写字母返回原值
其他判断 isupper(ch) 判断是否为大写字母
islower(ch) 判断是否为小写字母

5.2 实战示例


#include <iostream>
#include <cctype>
using namespace std;

int main() {
    char ch1 = 'A', ch2 = '5', ch3 = ' ', ch4 = 'b';

    // 字符类型判断
    cout << "isalpha('A'): " << isalpha(ch1) << endl; // 非0(是字母)
    cout << "isdigit('5'): " << isdigit(ch2) << endl; // 非0(是数字)
    cout << "isspace(' '): " << isspace(ch3) << endl; // 非0(是空白)
    cout << "islower('b'): " << islower(ch4) << endl; // 非0(是小写)

    // 大小写转换
    cout << "toupper('b'): " << (char)toupper(ch4) << endl; // B
    cout << "tolower('A'): " << (char)tolower(ch1) << endl; // a

    // 实战:遍历字符串,统计字母/数字/空格数量
    char str[] = "Hello 123 World!";
    int letter = 0, digit = 0, space = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        if (isalpha(str[i])) letter++;
        else if (isdigit(str[i])) digit++;
        else if (isspace(str[i])) space++;
    }
    cout << "\n字母数量:" << letter << endl;  // 10
    cout << "数字数量:" << digit << endl;    // 3
    cout << "空格数量:" << space << endl;    // 2

    return 0;
}
        

六、随机数库cstdlib

6.1 随机数生成函数

cstdlib库提供随机数生成功能,需包含头文件 #include <cstdlib>,核心函数:

函数名 功能说明
rand() 生成0 ~ RAND_MAX(通常为32767)之间的随机整数
srand(seed) 设置随机数种子,用于避免rand()生成固定序列

关键技巧:通常用time(NULL)作为种子(结合ctime库),确保每次运行生成不同随机数序列;生成指定范围随机数公式:
rand() % (max - min + 1) + min(生成[min, max]区间的随机整数)。

6.2 实战示例


#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    // 设置随机数种子(仅需调用一次)
    srand((unsigned int)time(NULL));

    // 生成0~99的随机数
    int rand1 = rand() % 100;
    cout << "0~99随机数:" << rand1 << endl;

    // 生成1~10的随机数
    int rand2 = rand() % 10 + 1;
    cout << "1~10随机数:" << rand2 << endl;

    // 生成100~200的随机数
    int rand3 = rand() % 101 + 100;
    cout << "100~200随机数:" << rand3 << endl;

    // 生成5个随机数序列
    cout << "\n5个随机数序列:";
    for (int i = 0; i < 5; i++) {
        cout << rand() % 50 << " ";
    }
    cout << endl;

    return 0;
}
        

七、时间库ctime

7.1 时间获取/转换函数

ctime库提供时间相关操作,需包含头文件 #include <ctime>,核心函数/类型:

函数/类型 功能说明
time_t 时间类型,存储从1970-01-01 00:00:00到当前的秒数(时间戳)
time(NULL) 获取当前系统时间戳(返回time_t类型)
ctime(&time_val) 将时间戳转换为人类可读的字符串(如 "Wed Oct 11 12:00:00 2024")
localtime(&time_val) 将时间戳转换为本地时间结构体(tm),包含年/月/日/时/分/秒

7.2 实战示例


#include <iostream>
#include <ctime>
using namespace std;

int main() {
    // 获取当前时间戳
    time_t now = time(NULL);
    cout << "当前时间戳:" << now << endl;

    // 转换为字符串格式
    cout << "当前时间(字符串):" << ctime(&now);

    // 转换为tm结构体,解析具体时间
    tm* local = localtime(&now);
    // 年份:tm_year = 实际年份 - 1900
    cout << "年份:" << local->tm_year + 1900 << endl;
    // 月份:tm_mon 0~11(0=1月,11=12月)
    cout << "月份:" << local->tm_mon + 1 << endl;
    cout << "日期:" << local->tm_mday << endl;
    cout << "小时:" << local->tm_hour << endl;
    cout << "分钟:" << local->tm_min << endl;
    cout << "秒数:" << local->tm_sec << endl;
    // 星期:tm_wday 0~6(0=周日,1=周一...6=周六)
    cout << "星期:" << local->tm_wday << endl;

    // 计算程序运行时间
    clock_t start = clock(); // 记录开始时间(时钟周期)
    // 模拟耗时操作
    for (int i = 0; i < 100000000; i++);
    clock_t end = clock();
    double duration = (double)(end - start) / CLOCKS_PER_SEC;
    cout << "\n程序运行时间:" << duration << " 秒" << endl;

    return 0;
}
        

八、输入输出库cstdio

8.1 sprintf/sscanf函数

cstdio是C风格输入输出库,sprintf/sscanf是核心字符串格式化函数,需包含头文件 #include <cstdio>

函数名 功能说明 语法
sprintf 将格式化数据写入字符数组(字符串拼接/格式化) sprintf(dst, 格式字符串, 变量1, 变量2...)
sscanf 从字符数组中按格式读取数据到变量 sscanf(src, 格式字符串, &变量1, &变量2...)

常用格式符:%d(整数)、%f(浮点数)、%s(字符串)、%c(字符)、%.2f(保留2位小数)。

8.2 实战示例


#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    // 1. sprintf:格式化写入字符串
    char buf[100];
    int age = 18;
    double score = 92.5;
    char name[] = "张三";
    
    sprintf(buf, "姓名:%s,年龄:%d,成绩:%.2f", name, age, score);
    cout << "sprintf结果:" << buf << endl; // 姓名:张三,年龄:18,成绩:92.50

    // 2. sscanf:从字符串读取数据
    char str[] = "李四,20,88.0";
    char name2[20];
    int age2;
    double score2;
    // 按格式解析(逗号分隔)
    sscanf(str, "%[^,],%d,%lf", name2, &age2, &score2);
    cout << "\nsscanf解析结果:" << endl;
    cout << "姓名:" << name2 << endl;   // 李四
    cout << "年龄:" << age2 << endl;    // 20
    cout << "成绩:" << score2 << endl;  // 88

    // 3. 实战:数字转字符串
    int num = 12345;
    char numStr[20];
    sprintf(numStr, "%d", num);
    cout << "\n数字转字符串:" << numStr << endl; // "12345"

    // 4. 实战:字符串转数字
    char strNum[] = "6789";
    int res;
    sscanf(strNum, "%d", &res);
    cout << "字符串转数字:" << res << endl; // 6789

    return 0;
}
        

注意:sprintf需确保目标数组空间足够;sscanf的%[^,]表示读取到逗号为止(非贪婪匹配),适用于分隔符解析。

九、注意事项

十、总结

掌握这些常用函数库,能大幅提升C++开发效率,覆盖数值计算、字符串处理、随机数、时间操作、输入输出等高频场景。实际开发中需结合场景选择合适的函数,并注意内存安全和跨平台兼容。


返回顶部