当前位置: 首页 > news >正文

算法竞赛常用函数整理(C++)

这篇文章转载自https://www.cnblogs.com/zyihan-crz/p/18763445作者总结的很好本人收藏学习并且自己补充一点尊重知识版权推荐大家看原作者文章。目录1.memset2.to_string3.isdigit4.sqrt5.exp6.pow7.log、log108.abs、fabs9.ceil、floor、round10.modf、fmod11.rand12.sort13.lower_bound、upper_bound14.reverse15.max_element、min_element16.__builtin_popcount、__builtin_popcountllGCC 扩展17.stoi、stoll、stof18.mt19937随机数生成器19.gcd、lcm20.next_permutation、prev_permutation21.string 成员函数substr、find、c_str22.unordered_map哈希映射23.islower/isupper大小写判断函数24.tolower/toupper大小写转换函数1.memset作用将指定内存块的前num个字节设置为指定值头文件#include cstring使用void* memset(void* ptr, int value, size_t num); // ptr目标内存块的起始地址 // value要设置的值以字节为单位 // num要设置的字节数例子// 将数组全部初始化为0 int arr[100]; memset(arr, 0, sizeof(arr)); // 将字符数组初始化为* char str[50]; memset(str, *, 10); // 前10个字节设为*注意事项按字节设置不适合初始化非字符类型的复杂值如-1对int有效因补码一致不能直接用于vector需用vector.assign或fillC 版本C982.to_string作用将数字常量转换为字符串头文件#include string使用string to_string(int val); string to_string(long val); string to_string(long long val); string to_string(float val); string to_string(double val); // 支持多种数值类型转换例子string s1 to_string(123); // s1 123 string s2 to_string(3.14); // s2 3.140000 string s3 to_string(-456LL); // s3 -456注意事项浮点数转换会包含默认精度如double保留 6 位小数C 版本C113.isdigit作用判断字符是否为数字0-9头文件#include cctype使用int isdigit(int c); // c为字符的ASCII值返回非0表示是数字0表示不是例子string s abc123def45; int cnt 0; for (char c : s) { if (isdigit(c)) cnt; // 统计数字个数结果为5 }注意事项需传入char的 ASCII 值直接传字符变量即可对负数或非字符值行为未定义C 版本C984.sqrt作用计算平方根头文件#include cmath使用double sqrt(double x); float sqrt(float x); long double sqrt(long double x);例子double res1 sqrt(25.0); // res1 5.0 float res2 sqrt(10.0f); // res2 ≈ 3.16228f注意事项输入x需非负否则返回 NaN浮点数C 版本C985.exp作用计算自然常数e的x次方e^x头文件#include cmath使用double exp(double x); float exp(float x); long double exp(long double x);例子double res exp(1.0); // res ≈ 2.71828e^1C 版本C986.pow作用计算x的y次方x^y头文件#include cmath使用double pow(double x, double y); float pow(float x, float y); long double pow(long double x, long double y);例子double res1 pow(2.0, 3.0); // res1 8.02^3 double res2 pow(10.0, 2.5); // res2 ≈ 316.22776610^2.5注意事项若x为负数且y非整数结果为 NaNC 版本C987.log、log10作用log计算自然对数ln xlog10计算以 10 为底的对数lg x头文件#include cmath使用double log(double x); // ln x double log10(double x); // lg x例子double res1 log(exp(1.0)); // res1 1.0ln e 1 double res2 log10(1000.0); // res2 3.0lg 1000 3注意事项输入x必须为正数否则返回 NaNC 版本C988.abs、fabs作用abs计算整数绝对值fabs计算浮点数绝对值头文件#include cmath // fabs #include cstdlib // abs整数或直接用std::absC11使用// 整数绝对值 int abs(int x); long abs(long x); long long abs(long long x); // 浮点数绝对值 double fabs(double x); float fabs(float x);例子int a abs(-5); // a 5 double b fabs(-3.14); // b 3.14C 版本C989.ceil、floor、round作用ceil(x)向上取整返回大于等于x的最小整数floor(x)向下取整返回小于等于x的最大整数round(x)四舍五入到最近整数头文件#include cmath使用double ceil(double x); double floor(double x); double round(double x);例子double c ceil(2.3); // c 3.0 double f floor(2.7); // f 2.0 double r round(2.5); // r 3.0C 版本C9810.modf、fmod作用modf(x, iptr)拆分x为整数部分通过iptr返回和小数部分返回值fmod(x, y)计算x除以y的余数x k*y 余数余数与x同号头文件#include cmath使用double modf(double x, double* iptr); double fmod(double x, double y);例子// modf示例 double x 3.14, int_part; double frac_part modf(x, int_part); // int_part 3.0frac_part 0.14 // fmod示例 double rem fmod(7.5, 2.0); // rem 1.57.5 3*2.0 1.5C 版本C9811.rand作用生成伪随机整数范围 0~RAND_MAX通常为 32767头文件#include cstdlib使用int rand(void);例子// 生成1~100的随机数 srand(time(0)); // 用当前时间初始化随机数种子 int num rand() % 100 1; // 范围[1, 100]注意事项需用srand初始化种子通常结合time(0)否则每次运行结果相同随机性较差竞赛中建议用mt19937见下文C 版本C9812.sort作用对区间内元素进行排序默认升序可自定义排序规则头文件#include algorithm使用// 对数组排序 void sort(RandomAccessIterator first, RandomAccessIterator last); // 自定义排序规则 void sort(RandomAccessIterator first, RandomAccessIterator last, Compare cmp);例子// 数组排序 int arr[] {3, 1, 4, 1, 5}; sort(arr, arr 5); // 升序[1,1,3,4,5] // vector排序 vectorint v {5, 2, 7}; sort(v.begin(), v.end(), greaterint()); // 降序[7,5,2] // 自定义结构体排序Lambda表达式 struct Point { int x, y; }; vectorPoint pts {{2,3}, {1,4}, {3,1}}; sort(pts.begin(), pts.end(), [](const Point a, const Point b) { return a.x b.x; // 按x升序 });注意事项自定义比较函数cmp作为类成员时需加static修饰Lambda 表达式比普通函数效率更高C 版本C9813.lower_bound、upper_bound作用在有序区间内进行二分查找lower_bound返回第一个大于等于目标值的元素位置upper_bound返回第一个大于目标值的元素位置头文件#include algorithm使用// 查找[first, last)中首个val的位置 ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T val); // 查找[first, last)中首个val的位置 ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T val);例子vectorint v {1, 3, 5, 5, 7}; // 查找5的第一个位置 auto it1 lower_bound(v.begin(), v.end(), 5); // 指向索引2值5 // 查找5的第一个位置 auto it2 upper_bound(v.begin(), v.end(), 5); // 指向索引4值7 int pos1 it1 - v.begin(); // pos1 2 int pos2 it2 - v.begin(); // pos2 4注意事项需确保区间已排序升序否则结果未定义C 版本C9814.reverse作用反转区间内元素的顺序头文件#include algorithm使用void reverse(BidirectionalIterator first, BidirectionalIterator last);例子// 反转数组 int arr[] {1,2,3,4}; reverse(arr, arr 4); // 结果[4,3,2,1] // 反转字符串 string s hello; reverse(s.begin(), s.end()); // 结果ollehC 版本C9815.max_element、min_element作用max_element返回区间内最大值的迭代器min_element返回区间内最小值的迭代器头文件#include algorithm使用ForwardIterator max_element(ForwardIterator first, ForwardIterator last); ForwardIterator min_element(ForwardIterator first, ForwardIterator last);例子vectorint v {3, 1, 4, 2}; // 找最大值 auto max_it max_element(v.begin(), v.end()); int max_val *max_it; // 4 int max_pos max_it - v.begin(); // 2索引 // 找最小值 auto min_it min_element(v.begin(), v.end()); int min_val *min_it; // 1 int min_pos min_it - v.begin(); // 1索引注意事项若有多个相同最值返回第一个出现的位置C 版本C9816.__builtin_popcount、__builtin_popcountllGCC 扩展作用计算整数二进制表示中 1 的个数内置位运算函数头文件无GCC 编译器内置使用int __builtin_popcount(unsigned int x); // 32位无符号整数 int __builtin_popcountll(unsigned long long x); // 64位无符号整数例子int cnt1 __builtin_popcount(0b1010); // 2二进制1010有2个1 int cnt2 __builtin_popcountll(0b111000ULL); // 364位下111000有3个1注意事项仅 GCC 编译器支持输入需为无符号整数C 版本GCC 扩展兼容 C9817.stoi、stoll、stof作用将字符串转换为整数 / 长整数 / 浮点数头文件#include string使用int stoi(const string str, size_t* pos 0, int base 10); // 转int long long stoll(const string str, size_t* pos 0, int base 10); // 转long long float stof(const string str, size_t* pos 0); // 转float例子int a stoi(123); // 123 long long b stoll(123456789012); // 123456789012 float c stof(3.14); // 3.14f // 指定进制如二进制1010转十进制 int d stoi(1010, nullptr, 2); // 10注意事项字符串格式错误或超出范围会抛异常C 版本C1118.mt19937随机数生成器作用高性能伪随机数生成器梅森旋转算法头文件#include random使用std::mt19937 rng(seed); // seed为种子通常用std::random_device{}()例子// 初始化随机数生成器 std::random_device rd; std::mt19937 rng(rd()); // 用硬件随机种子初始化 // 生成[1, 100]的随机整数 std::uniform_int_distributionint dist(1, 100); int num dist(rng); // 每次调用生成不同随机数注意事项随机性远优于rand()竞赛中优先使用C 版本C1119.gcd、lcm作用gcd(a,b)计算最大公约数lcm(a,b)计算最小公倍数头文件#include numeric使用templateclass T T gcd(T a, T b); // C17 templateclass T T lcm(T a, T b); // C17例子int g gcd(12, 18); // 6 int l lcm(12, 18); // 36注意事项输入需为非负整数lcm计算为(a/gcd(a,b))*b避免溢出C 版本C1720.next_permutation、prev_permutation作用生成区间的下一个 / 上一个字典序排列需已排序头文件#include algorithm使用bool next_permutation(BidirectionalIterator first, BidirectionalIterator last); bool prev_permutation(BidirectionalIterator first, BidirectionalIterator last);例子string s 123; next_permutation(s.begin(), s.end()); // s 132下一个排列 prev_permutation(s.begin(), s.end()); // s 123上一个排列注意事项若已为最后 / 最前排列返回false否则返回true并修改区间C 版本C9821.string 成员函数substr、find、c_str作用substr截取子字符串find查找子串位置c_str转换为 C 风格字符串const char*头文件#include string使用// 截取子串从pos开始长度为len默认到结尾 string substr(size_t pos 0, size_t len npos) const; // 查找子串从pos开始找str返回位置未找到返回string::npos size_t find(const string str, size_t pos 0) const; // 转换为C风格字符串 const char* c_str() const;例子string s abcdef; string sub s.substr(1, 3); // bcd从索引1开始取3个字符 size_t pos s.find(cd); // 2cd在索引2开始 const char* cstr s.c_str(); // 转换为const char*用于printf等C 版本C9822.unordered_map哈希映射作用存储键值对支持 O (1) 平均复杂度的插入、查找、删除头文件#include unordered_map常用操作// 插入键值对 void insert(const pairKey, Value p); // 访问/插入值若键不存在则默认构造 Value operator[](const Key key); // 查找键返回迭代器 iterator find(const Key key); // 删除键 size_t erase(const Key key);例子unordered_mapstring, int mp; mp[apple] 5; // 插入键值对apple,5 mp.insert({banana, 3}); if (mp.find(apple) ! mp.end()) { cout mp[apple]; // 输出5 } mp.erase(banana); // 删除键banana注意事项无序存储键需支持哈希自定义类型需提供哈希函数C 版本C1123.islower/isupper大小写判断函数作用用于检查一个字符是否为小写字母或大写字母返回布尔类型值。头文件#include cctype例子#include iostream #include cctype int main() { char c1 a; char c2 A; if (islower(c1)) { std::cout is lowercase letter std::endl; }else { std::cout not a lowercase letter std::endl; } if (isupper(c2)) { std::cout is uppercase letter std::endl; }else { std::cout not a uppercase letter std::endl; } return 0; }24.tolower/toupper大小写转换函数作用tolower(char c)可以将c转换为小写字母如果c是小写字母则不进行操作toupper函数同理。ASCII码表转换大小写使用c-Aa; c-aA;字符1变成数字1 可以1-0头文件#include cctype例子#include iostream #include cctype int main() { char c1 A; char c2 b; char lowercasec1 tolower(c1); std::cout c1 的小写形式为 lowercasec1 std::endl; char uppercasec2 toupper(c2); std::cout c2 的大写形式为 uppercasec2 std::endl; return 0; }
http://www.gsyq.cn/news/1393533.html

相关文章:

  • 小样本学习与注意力机制在婴儿表情识别中的实战应用
  • Spring 项目配置方式及优先级(案例)
  • KaTrain围棋AI训练平台:解锁你的围棋潜能,用AI提升棋力!
  • 垃圾处理设备综合实力TOP榜发布:河南多瑙河机械深耕陈腐填埋垃圾治理成行业标杆 - 新闻快传
  • 2026年南通短视频代运营与本地获客服务商深度横评指南 - 优质企业观察收录
  • VS Code智能编程扩展:从代码补全到AI生成的全方位效率提升指南
  • av1编码--编码块的预测约束条件
  • 《多智能体系统实战:我用10个智能体搭建了一个自动赚钱的AI公司》
  • CZSC缠论量化插件:如何用算法自动化解决传统缠论分析的三大难题
  • 黄金变现窗口期开启,深圳五大回收平台真实测评! - 奢侈品回收测评
  • 汽车零部件自动化落地案例|3D视觉引导蓄能器抓取
  • 如何用ChanlunX免费缠论插件实现通达信智能技术分析
  • 深度解析:导热硅脂丝印工艺 原理、优势及应用实践 - 资讯速览
  • 上海小程序开发|定制公司哪家好?2026推荐十家小程序制作公司高品质精准盘点 - 新闻快传
  • 2026 年 5 月企业培训平台怎么选?避开选型踩坑难题 - 讲清楚了
  • 观察 Taotoken 在不同时段与地区的 API 响应延迟情况
  • FanControl智能温控系统完整指南:告别噪音与高温的终极解决方案
  • 小电视空降助手:B站视频广告跳过插件终极指南
  • 终极CS2外部辅助开发框架:深度解析内存操作与图形界面集成
  • 单图扩散模型实战:多尺度与提示学习实现精准图像编辑
  • 泛微OA-E9与第三方系统集成开发企业级实战记录(十四)
  • Linux的权限基本概念
  • 从游戏客户端到技术美术:我在完美世界内部转岗的真实经历与学习路径分享
  • FlashAttention与蛋白质工程:解码生命密码的智能钥匙
  • 从思维到代码:面向对象核心思想学习笔记
  • 2026 GEO 行业口碑推荐:真实企业测评 + 靠谱公司判断指南
  • 【AI】Claude Code接入DeepSeek
  • YOLO科研创新指南
  • 数据结构(1)
  • UE5 PhysicsControl物理动画保姆级教程:从插件开启到蓝图配置,手把手教你让角色动起来