读书笔记
容器
顺序容器:
vector
string
stack
queue
priority_queue
priority_queue是优先队列:但是怎么设置元素的优先级呢?
对于内置类型:可以使用greater<typename>,和less<typename>设置优先级。less是元素越大优先级越大。 greater元素越小优先级越大。
对于自定义类型:需要自己写operator< 函数
测试Code:
int main()
{
priority_queue<string, vector<string>, greater<string>> q;
q.push(string("a"));
q.push(string("b"));
q.push(string("c"));
q.push(string("d"));
while (!q.empty()) {
cout << q.top() << endl;;
q.pop();
}
}
/**
*will output:
a
b
c
d
*/
int main()
{
priority_queue<string, vector<string>, less<string>> q;
q.push(string("a"));
q.push(string("b"));
q.push(string("c"));
q.push(string("d"));
while (!q.empty()) {
cout << q.top() << endl;;
q.pop();
}
}
/*
*will output
d
c
b
a
*/
struct foo {
int a;
friend bool operator <(foo a, foo b) {
return a.a < b.a;
}
};
int main()
{
priority_queue<foo> q;
foo a;
a.a = 1;
q.push(a);
a.a = 2;
q.push(a);
a.a = 3;
q.push(a);
a.a = 4;
q.push(a);
while (!q.empty()) {
cout << q.top().a << endl;;
q.pop();
}
}
/*
* will output:
4
3
2
1
*/
struct foo {
int a;
friend bool operator <(foo a, foo b) {
return a.a < b.a;
}
};
int main()
{
priority_queue<foo> q;
foo a;
a.a = 1;
q.push(a);
a.a = 2;
q.push(a);
a.a = 3;
q.push(a);
a.a = 4;
q.push(a);
while (!q.empty()) {
cout << q.top().a << endl;;
q.pop();
}
}
/*
*will output
1
2
3
4
*/
关联容器:
map
multimap
unordered_map
unordered_multimap
set
multiset
unordered_set
unordered_multiset
这篇blog介绍了map和unordered_map:有兴趣的同学可以去看看:在PAT里使用map还是unordered_map?
pair
pair
可以用pair代替内含两个元素的结构体。
algorithm
max(),min(),abs()
max(x,y)返回x,y中最大值
min(x,y)返回x,y中最小值
abs(x)(in stdlib.h) 返回x(整型变量,int,long,long long)的绝对值
swap
swap(x,y)交换两元素
reverse
reverse(it1.it2)反转it1到it2之间的元素。
next_permutation
next_permutation(container)给出序列在全排列下的下一个序列。
next_permulation在没有下一个序列是会返回false
fill
fill(it1,it2,value)给容器it1到it2填充value
sort
sort(it1,it2,cmp)
如果,没有填cmp函数,且元素是可比较大小的,则按从小到大排序
// 从大到小
bool cmp(int a,int b){
return a>b;
}
//从小到大
bool cmp(int a,int b){
return a<b;
}
cmp一定要有健全的返回值。即无论是什么输入,都要返回true或false。
lower_bound,upper_bound
这两个函数一定要在有序容器类使用
lower_bound(first,last,val) 寻找[first,last)中第一个大于等于val的位置
upper_bound(first,last,val) 寻找[first,last)中第一个大于 val的位置
code:
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
int a[10]={1,2,2,3,3,3,5,5,5,5};
int *lowerpos =lower_bound(a,a+10,-1);
int *upperpos=upper_bound(a,a+10,-1);
printf("%d %d\n",lowerpos-a,upperpos-a);
lowerpos = lower_bound(a,a+10,1);
upperpos = upper_bound(a,a+10,1);
printf("%d %d\n",lowerpos-a,upperpos-a);
lowerpos = lower_bound(a,a+10,3);
upperpos = upper_bound(a,a+10,3);
printf("%d %d\n",lowerpos-a,upperpos-a);
lowerpos = lower_bound(a,a+10,4);
upperpos = upper_bound(a,a+10,4);
printf("%d %d\n",lowerpos-a,upperpos-a);
lowerpos = lower_bound(a,a+10,6);
upperpos = upper_bound(a,a+10,6);
printf("%d %d\n",lowerpos-a,upperpos-a);
}
/*
* 0,0
* 0,1
* 3,6
* 6,6
* 10,10
*/
完结撒花d=====( ̄▽ ̄*)b
这章很靠平时对于STL使用的积累。同学们可以去看看C++ Prime深入学习STL.