笔记——第五章(上)刘汝佳_算法竞赛入门经典_

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差异很小,主要是默认访问权限和继承方式不同。
//例 知识点解说详见 P106
struct Point{
    int x,y;
    Point(int x=0, int y=0):x(x),y(y){}//构造函数,特点:没有返回值;参数中的0是默认值,没有指明参数时相当于调用 Point(0,0) 来构造;
    //x(x)是简化写法,等同于 this->x = x
};
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集合
string s,buf;
for(int i=0;i<s.length();i++);//s.length()
    if(isalpha(s[i]))//判断是否是字母,大小写都行
        s[i]=tolower(s[i]);//转化成小写;相对应函数:toupper(p50 提示3-20)
stringstream ss(s);//能像使用cin一样使用ss
while(ss>>buf)
    dict.insert(buf);//向集合中插入元素
for(set<string>::iterator it=dict.begin();it!=dict.end();++it)//迭代器iterator的使用
    cout<<*it<<endl;

例题5-4 映射:map

  • p113
#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());//string也有begin()和end();也能用sort
if(!cnt.count(r))//set和map都有count操作
    cnt[r]=0;//1.map中的int型也要初始化;2.map用起来有点像数组

5.25 栈、队列与优先队列


例题5-5 栈

  • p115
#include<stack>
stack<int> s;
s.push(s.top());//push元素入栈;pop元素出栈;top查看栈顶元素;
s.pop();
  • 解题关键:集合->ID,用map实现,ID->集合,vector实现。
typedef set<int> Set;
map<Set,int> IDcache; // 把集合映射成ID
vector<Set> Setcache; // 根据ID取集
Setcache.push_back(x); // 添加新集合
return IDcache[x] = Setcache.size() - 1;//集合的ID就是在向量中的秩

#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)); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值