C++是一门庞大的语言,大多数语言特性和库函数在算法竞赛中都是用不到的(或者是可以避开的),
算法竞赛中有它自身的特点,
有人说,C++太复杂了,与其把C++学的一知半解,还不如把C语言的基础打好,。
C++博大精深,算法竞赛中大多数选手只会用到其中很少的特性,
本文的主要内容就是总结这些特性。虽然不是解题必须的,但是值得学习。
1.1.1 C++版框架
算法1-1 “a+b程序”
#include<cstdio>
int main() {
int a,b;
while(scanf("%d%d", &a, &b) == 2) printf("%d\n", a+b);
return 0;
}
C语言 ————》 C++
stdio.h ——–> cstdio (事实上,stdio.h仍然存在,但是C++中推荐的头文件是cstdio)
string.h ——-> cstring
math.h ——-> cmath
ctype.h ——> cctype
C++能编译大多数C语言程序,虽然C语言中大多数头文件在C++中仍然可以使用,但推荐的方法是在C头文件之前加一个小写的c字母,然后去掉.h的后缀。
算法1-2 连续判断一组数中的最小数
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100 + 10;
int A[maxn];
int main() {
long long a,b;
while(cin >> a >> b) {
cout << min(a,b) << "\n";
}
return 0;
}
其中,iostream提供了输入输出流,algorithm提供了一些常用的算法,例如代码中的min。
cin>>a 的含义是从标注输入中读取a ,它的返回值是一个“已经读取了a的新流”,然后从这个新流中继续读取b。
如果流已经读完,while循环将退出。
using namespace std; 名称空间,用来缓解复杂程序的组织问题,
C++中可以使用流简化输入输出操作。标准输入输出流在头文件iostream中定义,存在于名称空间std中
声明数组时,数组大小可以使用const声明的常数,
1.1.2 引用
交换两个变量的算法,
C语言,用指针解决
C++ “引用” 虽然功能上比指针弱,但是减少了出错的可能,提高了代码的可读性。
算法1-3 交换两个变量
#include<iostream>
using namespace std;
void swap2(int& a, int& b) {
int t = a; a = b; b = t;
}
int main() {
int a = 3, b = 4;
swap2(a, b);
cout << a << " " << b << "\n";
return 0;
}
如果在参数名之前加“&”符号,表示这个参数按照引用(by reference)的方式传递,而不是C语言里面的传值(by value)方式传递。
这样,在函数内改变参数的值,也会修改函数的实参。
C++中的引用就是变量的“别名”,可以在一定程度上代替C中的指针。例如,可以用“传引用”的方式让函数内直接修改实参。
1.1.3 字符串
例1-4 输入数据的每行包括包含若干个(至少一个)以空格隔开的整数,输出每行中所有整数之和。
每次读取一行,然后再扫描改行的字符,同时计算结果。
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main() {
string line;
while(getline(cin,line)) {
int sum = 0, x;
stringstream ss(line);
while(ss >> x) sum += x;
cout << sum << "\n";
}
return 0;
}
string类在string头文件中,而stringstream 在是stream头文件中。首先用getline函数读一行数据,然后用这一行创建一个“字符串流” —–ss。接下来只需要像读取cin那样读取ss即可。
1.1.4 结构体
#include<iostream>
using namespace std;
struct Point {
int x, y;
Point(int x=0, int y=0):x(x),y(y) {}
};
Point operator + (const Point &A, const Point &B) {
return Point(A.x+B.x,A.y+B.y);
}
ostream& operator << (ostream &out, const Point& p) {
out << "(" << p.x << "," << p.y << ")";
return out;
}
int main() {
Point a,b(1,2);
a.x = 3;
cout << a+b << "\n";
return 0;
}