知识
主要是感觉以后会用到但有可能忘的(就是不熟…)和老是出错的做一些摘录。
set、multiset用<set>/map、multiset用<map>/queue、priority_queue
用<queue>
priority_queue是大根堆:保证最前面对元素是“最大的”,注意其余的不是单调的,并且是实时排序的(目前感觉只在快速求最大值时有用…)
erase(elem)、erase(pos): 可以用于set和map 地址和元素都可以
sort(begin, end,cmp);//bengin和end是地址,常为指针或迭代器(前开后闭)
bool cmp(int a, int b){
return a > b;//降序;默认升序
}
bool next_permutation(begin, end);
改变区间内元素的顺序,产生下一个排列。
bool prev_permutation(begin, end);
产生前一个排列。【如果想生成全排列的话需要先对原列排序
end为最后一个元素的下一个位置。
upper_bound(begin, end, value);
返回>value的元素的第一个位置。
lower_bound(begin, end, value);
返回>=value的元素的第一个位置。
num[] = {1,2,2,3,4,5};
lower_bound(num, num + 6, 2)为num + 1
upper_bound(num, num + 6, 2)为num + 3
关于操作符重载的两个例子
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
struct T1{
int key;
int value1, value2;
bool operator<(const T1 &b)const{
return (key < b.key);
}
};
int main(){
set<T1> s;
set<T1> ::iterator iter1;
T1 t={2,33,44};
T1 tt;
tt.key=5;
tt.value1=22;
tt.value2=88;
s.insert(t);
s.insert(tt);
cout << "ITERATE:" << endl;
for (iter1 = s.begin(); iter1 != s.end(); iter1++){
cout << (*iter1) .key<<" "<< (*iter1).value1<<" "<< (*iter1).value2<< endl;
}
cout << "FIND:" << endl;
iter1 = s.find(t);
if(iter1 != s.end()) {
cout << (*iter1) .key<<" "<< (*iter1).value1<<" "<< (*iter1).value2<< endl;
}else{
cout << "NOT FOUND" << endl;
}
return 0;
}
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
#define pow2(a) ((a)*(a))
#define dist2(x, y) (pow2(x) + pow2(y))
struct coord{
int x, y;
const bool operator<(const coord &b)const{
return (dist2(x, y) < dist2(b.x, b.y));
}
};
int main(){
priority_queue<coord> s;
coord a;
a.x = 3, a.y = 2;
s.push(a);
a.x = 1, a.y = 2;
s.push(a);
a.x = 2, a.y = 2;
s.push(a);
cout << "Size: " << s.size() << endl;
cout << "Top: " << s.top().x << ", " << s.top().y << endl;
s.pop();
cout << "Top: " << s.top().x << ", " << s.top().y << endl;
return 0;
}
记录
初步学习了stl的基础语法,不是很熟练。迭代器整理了一些东西,感觉除了当指针用就没啥其他用法了,太琐碎就不贴了。操作符重载和stringstream还没搞懂,所以现在写容器的循环嵌套经常报错。还需要补一些结构体的知识。做题中用到了hash、欧拉函数,完全不会……