竞赛中 C++常用函数(打 ACM 和 CCSP 的同学快看)
C 与 C++的区别
虽然同为 C 大家族的成员,但 C++和 C 用起来确实有较大差别。例如,C++中有许多内置函数库可以直接调用,而 C 语言的大多数函数需要自己定义。在 C++中,我们可以尽情地使用函数库,极大地方便了竞赛编程。
下面给大家总结一些竞赛中常用的 C++函数,希望对初学者有所帮助。
基本函数篇
1. 排序函数 sort
sort()
是 C++中用于对指定区间内所有元素进行排序的函数(默认升序)。区间使用迭代器或指针表示,比如对于数组 a[n]
,想要对它排序,可以写:
如果想要降序排序,可以自定义比较函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <bits/stdc++.h> using namespace std;
bool cmp(int a, int b) { return a > b; }
int main() { int n = 5; int a[] = {3, 1, 4, 5, 2}; sort(a, a + n, cmp); for (int i = 0; i < n; i++) cout << a[i] << " "; return 0; }
|
字符串排序:
1 2 3 4 5 6 7 8 9
| #include <bits/stdc++.h> using namespace std;
int main() { vector<string> strs = {"apple", "banana", "cherry"}; sort(strs.begin(), strs.end()); sort(strs.begin(), strs.end(), greater<string>()); return 0; }
|
2. 快速求最大值与最小值 max
和 min
1 2 3
| int a = 10, b = 20; cout << max(a, b) << endl; cout << min(a, b) << endl;
|
3.求绝对值 abs
1 2
| int x = -5; cout << abs(x) << endl;
|
对于浮点数用 fabs
:
1 2 3
| #include <cmath> double y = -3.14; cout << fabs(y) << endl;
|
4. 字符串转整数 stoi
和整数转字符串 to_string
1 2 3 4 5
| string s = "12345"; int num = stoi(s);
int x = 6789; string str = to_string(x);
|
5. 数学常用函数
1 2 3 4 5
| #include <cmath> cout << sqrt(16) << endl; cout << pow(2, 10) << endl; cout << ceil(3.14) << endl; cout << floor(3.14) << endl;
|
6. 判断字符类型
1 2 3 4 5
| char c = 'A'; if (isdigit(c)) cout << "数字" << endl; if (isalpha(c)) cout << "字母" << endl; if (islower(c)) cout << "小写字母" << endl; if (isupper(c)) cout << "大写字母" << endl;
|
7. 数组初始化
1 2 3
| int a[100]; memset(a, 0, sizeof(a)); memset(a, -1, sizeof(a));
|
8. 常用 STL 容器
1 2 3 4
| vector<int> v; v.push_back(1); v.push_back(2); cout << v.size() << endl;
|
1 2 3 4 5 6
| set<int> s; s.insert(3); s.insert(1); s.insert(3); for(auto x : s) cout << x << " ";
|
1 2 3 4
| map<string, int> mp; mp["apple"] = 3; mp["banana"] = 5; cout << mp["apple"] << endl;
|
9. 常用位运算技巧
1 2
| if (x & 1) cout << "奇数" << endl; else cout << "偶数" << endl;
|
1 2
| int z = x << 1; int w = x >> 1;
|
10. 快速读写优化(竞赛中常用)
1 2
| ios::sync_with_stdio(false); cin.tie(nullptr);
|
放在 main 函数开头,可以加快 cin 和 cout 的速度,避免超时。
总结
以上是竞赛中比较常用的 C++基础函数和技巧,掌握它们能帮助你快速写出高效、简洁的代码。如果你想了解更高级的函数和数据结构,也欢迎留言告诉我!
欢迎收藏转发,助力你的 ACM 和 CCSP 之路!