本文讲解一些在ACM中C++的应用。
1 algorithm头文件
swap()函数不仅同时支持int、double等所有内置类型,甚至还支持用户自己编写的结构体。
2 stringstream
参考:C++编程语言中stringstream类介绍
例子:输入数据的每行包含若干个(至少一个)以空格隔开的整数,输出每行中所有整数之和。
sol:两种方案:一是使用getchar(边读边算,代码较短;二是每次读取一行,然后再扫描该行的字符,同时计算结果。
#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;
}其中,getline()函数是读取一行数据(可以行空格)。
注意:虽然string和sstream都很方便,但string很慢,sstream更慢,应谨慎使用。
3 C++中的结构体
除了可以有变量(称为成员变量)之外还可以有函数(称为成员函数)。
struct Point{
	int x,y;
	Point(int x=0,int y=0):x(x),y(y) {} //构造函数
    //也可以写成
  //Point(int x=0,int y=0){ this->x=x; this->y=y; }
}; 声明Point a,b(1,2)时,分别调用了Point()和Point(1,2)。其中x=0,y=0意味默认x,y值为0,Point()相当于Point(0,0)。其中“:x(x),y(y)”是简单写法。
4 模板
sum函数
初级版本:
#include<bits/stdc++.h>
using namespace std;
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; 
}
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(){
	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) << "\n";
	return 0;
}
进化版本:
#include<bits/stdc++.h>
using namespace std;
template<typename T>
T sum(T* begin, T* end){
	T ans = 0;
	for(T *p = begin; p != end; p++) ans = ans + *p;
	return ans; 
}
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){
	out << "(" << p.x << "," << p.y <<")";
	return out;
}
int main(){
	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;
}
5 STL初步
学习资料:
ACM常用STL
最全ACM常用STL
常用:
| stack | 
| queue | 
| priority_queue | 
| vector | 
| set | 
| map | 
| sort | 
| lower_bound / upper_bound | 










