蓝桥杯省赛备战-常用函数


1.

printf("%03d\n", x);  

%03d中的3表示最少输出三位数字,0表示如果数字不足3位,在最左边用0补足。

printf("%5d\n");

其中%5d表示按照5位数打印,不足5位在前面补空格。


2.

scanf()函数的返回值是读入的变量个数
常这样使用

while(scanf("%d", &x) == 1) {//处理输入
}

或者

while(scanf("%d%d", &m, &n) == 2) {//处理输入
}

3.

输出程序所用时间(s)

#include
#includeint main() {printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC);return 0;
}

4.

调试的时候利用文件重定向的输入输出

工具-编译选项-编译时加入一下命令 -DLOCAL
将以下代码放入main函数

#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif

5.

精确到小数点后n位,其中星号表示不确定的位数

printf("%.*f\n", n,x); //n用来确定小数点后的位数

6.

数组a复制k个元素到数组b

memcpy(b, a, sizeof(int)*k); //int数组,其它类型的数组同理

数组a全部复制到数组b

memcpy(b, a, sizeof(a));

7.

把数组清零

memset(a, 0, sizeof(a))

把数组置1

memset(a, 1, sizeof(a))

把数组置-1

memset(a, -1, sizeof(a))

memset只能快速重置int数组的这三个值,其他值用fill函数来重置或初始化。


8.

使用fill函数初始化数组

方法为 fill(arr, arr+n, x),将arr数组第 [0, n) 位的值初始化为x

[0,n )为左闭右开的区间,若n=10,则为下标从0到9的值

#include
using namespace std;int a[10];int main() {fill(a, a+10, 2147483647);for(int i = 0; i < 10; i++) cout << a[i] << " ";return 0;
} 

该程序的输出为:

2147483647 2147483647 2147483647 2147483647 2147483647 2147483647 2147483647 2147483647 2147483647 2147483647

9.

读入一个字符

getchar()

一般这样使用

int c;
while((c = getchar()) != EOF) {//对输入进行处理
}

输出一个字符

putchar()

10.

判断某个字符

#includeint x;
isalpha(x); //判断参数是否是字母字符
isdigit(x); //判断参数是否是数字字符
islower(x); //判断参数是否是小写字母字符
isupper(x); //判断参数是否是大写字母字符

11.

转换为大写或小写

#include
int x;
tolower(x); //转换为小写字母
toupper(x); //转换为小写字母

12.

读入一个字符串,以空格或换行结束

scanf("%s", s);

常如下使用

char s[30];
while(scanf("%s", s) == 1) {//处理字符串s
}

13.

获取字符串长度

#includeint len = strlen(s);

14.

输出到字符串

#include
char buf[99];
int x;
sprintf(buf, "Hello world\n %d", x);

用法和printf类似,只是多了一个参数,表示要输出到的字符串(字符数组)。


15.

快速排序

sort(a, a+n);              //对a数组排序
sort(v.begin(), v.end());  //对vector排序

查找大于或者等于x的第一个位置(在已排序数组中)

int p = lower_bound(a, a+n, x) - a;

函数的名称 lower_bound 即 “下界”

头文件是

#include
using namespace std;

16.

字符串比较 strcmp()

#include
#includeint main() {char s1[] = "this is a string";char s2[] = "this is a string";char s3[] = "this is a str";printf("%d\n", strcmp(s1, s2));  //相等,输出0 printf("%d\n", strcmp(s1, s3));  //大于,输出大于0 printf("%d\n", strcmp(s3, s1));  //小于,输出小于0return 0;
} 

输出为

0
1
-1

17.

生成全排列 next_permutation(a,a+n),用于暴力枚举

#include
#include //包含 next_permutation
using namespace std;int main() {int n, p[100];scanf("%d", &n);for(int i = 0; i < n; i++) scanf("%d", &p[i]);sort(p, p+n);                                       //排序,得到p得最小排列do {for(int i = 0; i < n; i++) printf("%d ", p[i]); //输出排列pprintf("\n"); } while(next_permutation(p, p+n));                  //求下一个排列 return 0;
} 

输入
3
1 2 3

输出为

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

参考书籍:《算法竞赛入门经典》刘汝佳


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部