第五章 C++与STL入门(例题篇:C++部分)
知识点一:
#include <cstdio>
int main()
{
int a, b;
while (scanf("%d%d", &a, &b) == 2)
printf("%d\n", a + b);
return 0;
}
和之前的C程序比较,唯一的区别是stdio.h变成了cstdio。事实上,stdio.h仍然存在,但是C++中推荐的头文件是cstdio。类似地,string.h变成了cstring,math.h变成了cmath,ctype.h变成了cctype。带.h后缀的头文件依然存在,但并不被C++所推荐使用。
知识点二:
//iostream提供了输入输出流
#include<iostream>
//algorithm提供了一些常用的算法
#include<algorithm>
//头文件iostream和algorithm里定义的内容放在了std名称空间里
using namespace std;
//C++的数组大小可以使用const声明的常数
const int maxn = 100 + 10;
int A[maxn];
int main()
{
/*C++流存在运行太慢的问题,不过流也可以加速,方法是关
闭和stdio的同步,即下面的调用。*/
ios::sync_with_stdio(false);
long long a, b;
while (cin >> a >> b)
{
cout << min(a, b) << "\n";
}
return 0;
}
知识点三:
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string line;
while (getline(cin, line))
{
int sum = 0, x;
stringstream ss(line);
while (ss >> x)
{
sum += x;
}
cout << sum << "\n";
}
return 0;
}
sting类在string头文件中,而stringstream在sstream头文件中。首先用getline函数读一行数据(相当于C语言中的fgets,但由于使用string类,无须指定字符串的最大长度),然后用这一行创建一个“字符串流”ss。接下来只需像读取cin那样读取ss即可。
虽然string和sstream都很方便,但string很慢,sstream更慢,sstream更慢,应谨慎使用。
知识点四:
C++除了支持结构体struct之外,还支持类class。C++不再需要用typedef的方式定义一个struct,而且在struct里除了可以有变量(称为成员变量)之外还可以有函数(称为成员函数)。
事实上,在C++中struct和class最主要的区别是默认访问权限和继承方式不同,而其他方面的差异很小。
#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)
{
cout << "(" << p.x << "," << p.y << ")";
return out;
}
int main()
{
ios::sync_with_stdio(false);
Point a, b(1, 2);
a.x = 3;
cout << a + b << "\n";
return 0;
}
知识点五:
模板:
#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)
{
cout << "(" << p.x << "," << p.y << ")";
return out;
}
template<typename T>
T sum(T*begin, T*end)
{
T *p = begin;
T ans = 0;
for (T *p = begin;p != end;p++)
{
ans = ans + *p;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
double a[] = { 1.1,2.2,3.3,4.4 };
cout << sum(a, a + 4) << "\n";
Point b[] = { Point(1,2),Point(3,4),Point(5,6),Point(7,8) };
cout << sum(b, b + 4) << endl;
return 0;
}
结构体和类也可以是带模板。
#include<iostream>
using namespace std;
template <typename T>
struct Point {
T x, y;
Point(T x = 0, T y = 0) :x(x), y(y) {}
};
template <typename T>
Point<T> operator+(const Point<T>&A, const Point<T>&B)
{
return Point<T>(A.x + B.x, A.y + B.y);
}
template <typename T>
ostream& operator<<(ostream &out, const Point<T> &p)
{
cout << "(" << p.x << "," << p.y << ")";
return out;
}
int main()
{
ios::sync_with_stdio(false);
Point<int> a(1, 2), b(3, 4);
Point <double> c(1.1, 2.2), d(3.3, 4.4);
cout << a + b << " " << c + d << "\n";
return 0;
}