失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > C++中常用函数总结(头文件)

C++中常用函数总结(头文件)

时间:2022-11-21 22:31:18

相关推荐

C++中常用函数总结(头文件)

文章目录

1 algorithm1.1 函数1.2 代码示例2 cmath(c++) / math(c)2.1 函数2.2 代码示例3 cstring (c++)/ string(c)3.1 函数3.2 代码示例4 cctype5 iomanip

1 algorithm

1.1 函数

1.2 代码示例

#include<cstdio>#include<algorithm>#include<string>#include<functional>using namespace std;struct Node{int x,y;Node(int _x, int _y):x(_x), y(_y){}Node(){}}nodes[3];// 降序: x, 升序:ybool node_cmp(Node no1, Node no2){if(no1.x!=no2.x){return no1.x > no2.x;}else{return no1.y < no2.y;}}int main(){/*fill*/int a[10];int b[5][10];fill(a, a+10, 2);fill(b[0], b[0]+5*10, 2);/*next_permutation*/// 全排列string str="123";while(next_permutation(str.begin(),str.end())){printf("%s\n", str.c_str());}/*sort*/// 1. 自定义 比较函数cmpnodes[0] = Node(1, 2);nodes[1] = Node(1, 0);nodes[2] = Node(-1, 3);sort(nodes,nodes+3,node_cmp);for(int i=0;i<3;i++){printf("%d %d\n", nodes[i].x, nodes[i].y);}// 2. 用greater(降序)/less(升序、默认) #include<functional>sort(a,a+10,greater<int>());// int a[10];/*lower_bound、upper_bound*/int arr[4] = {1,2,2,3};int *p = lower_bound(arr, arr+4, 2); // 第一个>=2int *q = upper_bound(arr, arr+4, 2); // 第一个>2printf("%d %d\n", p-arr, q-arr);// 元素位置return 0;}

2 cmath(c++) / math(c)

2.1 函数

2.2 代码示例

#include<cstdio>#include<cmath>using namespace std;const double PI = acos(-1.0);double round_up_down(double x){return (x>0.0)?floor(x+0.5):ceil(x-0.5);}int main(){/*四舍五入(不是round函数)*/double db1 = round_up_down(1.5);printf("%f", db1);/*取整*/double x = 2.2;printf("%f %d %f %f\n", ceil(x),int(x),floor(x),round(x)); // 3.00000022.000000 2.000000x = 2.5;printf("%f %d %f %f\n", ceil(x),int(x),floor(x),round(x)); // 3.000000 22.0000003.000000// 整数x = 2.0;printf("%f %d %f %f\n", ceil(x),int(x),floor(x),round(x)); // 2.000000 2 2.000000 2.000000/*三角函数*/double db = sin(PI * 30 / 180); // db = sin(PI/6)printf("%f",db);return 0;}

3 cstring (c++)/ string(c)

3.1 函数

注:

sscanf 和 sprintf记忆技巧:

scanf("%d", &n); // 键盘 ——> n变量sscanf(str, "%d", &n);// str ——> n变量printf("%d", n);// n变量 ——> 屏幕sprintf(str, "%d", n);// n变量 ——> str

总结: 相当于键盘/屏幕是 str

3.2 代码示例

#include<cstdio>#include<cstring>using namespace std;int main(){/*memset*/int arr1[4], arr2[4][4];// 一维memset(arr1, 0, sizeof(arr1)); // sizeof(arr1) = 16 : 字节数 = 4*int// 二维memset(arr2, -1, sizeof(arr2));for(int i=0; i<4; i++){printf("%d\n", arr1[i]);}for(int i=0; i<4;i++){for(int j=0; j<4; j++){printf("%d ",arr2[i][j]);}printf("\n");}/*sscanf*/int n;double db;char chs[20] = "222:3.14:hello";char chs2[20];sscanf(chs,"%d:%lf:%s",&n,&db,chs2);//chs 转换为 n、db、chs2printf("%d %f %s\n",n,db,chs2);//sprintf(chs, "%d-%lf-%s",n,db,chs2);printf("%s\n", chs);return 0;}

4 cctype

5 iomanip

cout 控制输出精读(保留小数点几位)

#include<iostream>#include<iomanip>using namespace std;int main(){// 输出保留小数点 2 位double db = 2.5555;cout<<setiosflags(ios::fixed)<<setprecision(2)<<db;return 0;}

如果觉得《C++中常用函数总结(头文件)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。