5.1从C到C++
- C++推荐将.h后缀的头文件用c前缀替代,例如stdio.h->cstdio
- C++头文件iostream提供了输入流与输出流,最大优势是不需要占位符%d、%s等。最大的缺陷是慢。
- ”命名空间“ namespace的概念(见书本P102)
- algorithm头文件提供了常用算法,如min、sort等
- C++新增了bool数据类型
- 引用:相当于变量的”别名“,可在调用的函数中改变实参
void swap2(int &a, int &b){……}
int main(){
……
swap2(a,b);
}
- C++中的字符串——string(头文件string),用起来非常方便,速度稍慢。配合stringstream(头文件sstream)可以像cin一样读取。但sstream比string还要慢。
- C++中的结构体struct与class差异很小,主要是默认访问权限和继承方式不同。
struct Point{
int x,y;
Point(int x=0, int y=0):x(x),y(y){}
};
Point a,b(1,2);
- 模板,机试很少用到(又不是工程没必要搞这么复杂),但学习模板利于理解STL,全城Standard Template Library
例题5-1 排序和查找
- algorithm 提供的 sort 和lower_bound可以轻松解决。sort无需多言, lower_bound 是提供的多种二分查找中的一种, 故只适用于有序对象。
例题5-2 vector的使用
- 若a是一个vector,可用a.size()读取大小,a.resize()改变大小,a.back()读取末尾元素,a.push_back()在尾部添加元素,a.pop_back()删除最后一个元素。
例题5-3 集合:set
- p112
- set中每个元素至多只出现一次,并且已经从小到大拍好序
#include<set>
#include<string>
#include<cctype>
#include<sstream>
set<string> dict;
string s,buf;
for(int i=0;i<s.length();i++);
if(isalpha(s[i]))
s[i]=tolower(s[i]);
stringstream ss(s);
while(ss>>buf)
dict.insert(buf);
for(set<string>::iterator it=dict.begin();it!=dict.end();++it)
cout<<*it<<endl;
例题5-4 映射:map
#include<map>
map<string,int> month_name;
month_name["July"]=7;
#include<map>
#include<string>
#include<cctype>
#include<vector>
#include<algorithm>
map<string,int> cnt;
string ans;
sort(ans.begin(),ans.end());
if(!cnt.count(r))
cnt[r]=0;
5.25 栈、队列与优先队列
例题5-5 栈
#include<stack>
stack<int> s;
s.push(s.top());
s.pop();
- 解题关键:集合->ID,用map实现,ID->集合,vector实现。
typedef set<int> Set;
map<Set,int> IDcache;
vector<Set> Setcache;
Setcache.push_back(x);
return IDcache[x] = Setcache.size() - 1;
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
if (op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x));
if (op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x));
if (op[0] == 'A') { x = x2; x.insert(ID(x1)); }