小结 c++ stl(98) 在acm中的应用

来源:互联网 发布:中华武术 知乎 编辑:程序博客网 时间:2024/05/07 08:53

参考链接 http://www.cplusplus.com/reference/

topcoder中的两篇,写的非常好!A、B

容器:

容器中,size();empty();都是通用的。判断容器是否为空,用empty不要用size。

初始化stack和 queue 只能用pop,其他的可以用clear()

声明都是: 容器名 <数据类型变量名。

 

vector //在图中做邻接表  

定义:  vector<int>  v;

添加新元素到末尾: v.push_back(x);//不能用v[i] = x

访问元素: v[x]back();

更改已存在的元素: v[i] = x;

v.size();v.clear();empty();

 

map //hash,不可缺少,第一个键值必须是定义了 的数据类型(string ,pair,int)

定义: map<string, int> m;

访问:m[2] = 3// 访问一个元素前,如果需要先查找它在不在map中,可以用m.count(x) !=0;

删除元素:erase();

empty();size();clear();

 

set //去重

定义:set<int> s;

操作:insert(); erase()

empty();size();clear();

 

deque // 实现单调队列

定义: deque<int> dque;

操作:push_back(); pop_back(); push_front(); pop_front(); 

访问:front(); back();

大小:dque.size();clear();empty();

 

queue // bfs

定义:queue<int> q;

front();push();pop();

size();empty();

 

priority_queue // 优先队列

定义:priority_queue<int> pq;

top();push();pop();

size();empty();

 

stack // 使用比较少,单调栈?

定义:stack<int> s;

top();push();pop();

size();empty();

 

iterator // 要对容器做遍历访问,或者传参数需要 

定义:set<int>::iterator it;

常用:begin();end(); 

The following operations are defined for iterators:
get value of an iterator, int x = *it;
increment and decrement iterators it1++, it2--;
compare iterators by '!=' and by '<';
add an immediate to iterator it += 20; <=> shift 20 elements forward
get the distance between iterators, int n = it2-it1;

 

pair<int, int > // 定义数据类型

typedef pair<int,int> P;// 这样写起来比较方便

P p = make_pair(a, b); // 初始化赋值

p.first = a ;p.second =b;//访问元素

 

 

Algorithm:

所有的pos 可能是指针,也可能是迭代器

the useful macros would be:
 #define all(c) c.begin(), c.end() 


bool binary_search(begin, end, target); 

lower_bound(begin, end, target); // 返回第一个 >= target的位置

upper_bound(begin, end, target); // 返回第一个 > target的位置

 

int count(begin, end, target); // 计算数组中target的数目

//int count_if(begin, end, lambda); // lambda是一个返回bool的自定义函数

find(begin, end, target); // 返回第一次出现的指针(迭代器)

 

swap(x, y);

fill_n(a, size, val); //做初始化,memset更好用

repalce(begin, end, old_value, new_value); // 把所有old_value替换成new_value

reverse(begin, end);//反转

 

sort();

 

min(a, b);

max(a, b);

min_element(begin, end); //数组中的最小元素的位置

max_element(begin, end);

 

next_permutation(begin, end); //当还有下一个排列时,返回true,否则false

 Don’t forget to ensure that the elements in a container are sorted before your first call to next_permutation(...). Their initial state should form the very first permutation; otherwise, some permutations will not be checked. 

 

 

 

0 0
原创粉丝点击