set
set 自定义排序器
注:set触发自定义排序器是在插入时,如果想修改已在set中数据的排序元素,并希望重新排序。需要找到该元素并删除,再插入,才能触发排序
#include <iostream>
#include <set>
using namespace std;
const int maxn=50010;
struct node {
int num;
int ts;
// 重载<运算符,实现set自定义排序
bool operator < (const node & nd) const {
return nd.ts!=ts?ts>nd.ts:num<nd.num;
}
};
set<node> rcs; // 记录容器--记录排序后的查询结果
int book[maxn];// 记录重复次数--book[i]=t,第i个元素已重复出现t次
int main(int argc,char * argv[]) {
int n,k,a;
scanf("%d %d",&n,&k);
for(int i=0; i<n; i++) {
scanf("%d",&a);
if(i!=0) { //第一个查询不打印,之后的查询,打印结果
printf("%d:",a);
int cnt = 0;
for(auto it=rcs.begin(); cnt<k&&it!=rcs.end(); it++,cnt++)
printf(" %d",it->num);
printf("
");
}
auto it = rcs.find({a,book[a]}); //是否以前已经出现过
if(it!=rcs.end()) rcs.erase(it); //删除再插入,触发set自定义排序
rcs.insert({a,++book[a]});
}
return 0;
}
set遍历
#include <iostream>
#include<set>
using namespace std;
int main(){
int numList[6]={1,2,2,3,3,3};
//1.set add
set<int> numSet;
for(int i=0;i<6;i++)
{
//2.1insert into set
numSet.insert(numList[i]);
}
//2.travese set
for(set<int>::iterator it=numSet.begin() ;it!=numSet.end();it++)
{
cout<<*it<<" occurs "<<endl;
}
//3.set find useage
int findNum=1;
if(numSet.find(findNum)!=numSet.end())
{
cout<<"find num "<<findNum<<" in set"<<endl;
}else{
cout<<"do not find num in set"<<findNum<<endl;
}
//set delete useage
int eraseReturn=numSet.erase(1);
if(1==eraseReturn)
{
cout<<"erase num 1 success"<<endl;
}else{
cout<<"erase failed,erase num not in set"<<endl;
}
return 0;
}
map
map遍历
#include <iostream>
#include <map>
using namespace std;
int main(){
map<int,int> m;
for (int i = 0; i < 10; i++){
m[i] = i*i;
}
map<int,int>::iterator iter;
iter = m.begin();
while(iter != m.end()){
cout << iter->first << "-" << iter->second << endl;
iter++;
}
for (iter = m.begin();iter != m.end(); iter++){
cout << iter->first << "-" << iter->second << endl;
}
for(auto &it : m){
cout << it.first << "-" << it.second <<endl;
}
return 0;
}
queue
注意事项
哨兵
queue<string> q;
q.push("");
cout<<q.size(); //1