@lychee123
2017-10-02T13:44:32.000000Z
字数 1415
阅读 1247
STL
题意
给定一些要求如(插入,删除,输出,查找前驱或后继,清空,计数,查找等)通过STL里set的自带函数完成相应要求。
分析
该题是STL里set的经典练习,对初学STL的同学熟悉set里的函数有很大的帮助。
代码
#include<stdio.h>#include<string.h>#include<algorithm>#include<bits/stdc++.h>using namespace std;int main(){int x;char a[22];set<int>s;//定义int型集合s。(set可以是任何类型)往set里丢的数如果有相同的会保留一个,如果允许有相同的数,那么使用multiset.往set里丢的数默认从小到大排序的set<int>::iterator it;//迭代器it相当于一个指针while(~scanf("%s",a)){if(a[0]=='-')break;if(a[0]=='i'){scanf("%d",&x);s.insert(x);//insert()函数,代表插入某个数,如果该数已存在,忽略这一操作}if(a[0]=='d'){scanf("%d",&x);if(s.count(x)==0)//对x计数,如果个数为零表示未查找到printf("Input Error\n");elses.erase(x);//erase()函数是删除函数}if(a[0]=='s'){scanf("%d",&x);it=s.find(x);//查找x的地址附给指针itif(s.count(x)==0)printf("Input Error\n");else{it++;if(it==s.end())//set里最后一位的下一为s.end()printf("%d is the maximum\n",x);else{it=s.upper_bound(x);//s.upper_bound(x)返回大于x元素且与x最接近的数的迭代器printf("The successor of %d is %d\n",x,*it);}}}if(a[0]=='p'&&a[2]=='e'){scanf("%d",&x);it=s.find(x);if(s.count(x)==0)printf("Input Error\n");else{if(it==s.begin())printf("%d is the minimum\n",x);else{it=s.lower_bound(x);//返回指向大于(或等于)某值的第一个元素的迭代器it--;//由于该数x在set里存在所以it指向的为该数xprintf("The predecessor of %d is %d\n",x,*it);}}}if(a[0]=='p'&&a[2]=='i'){for(it=s.begin();it!=s.end();it++)//*s.begin()等于set里的第一个数,*s.end()==s.size()集合中元素的数目;printf("%d,",*it);//it是指针*it表示指针指向的数printf("end of print\n");}if(a[0]=='e'){printf("end of this test\n");s.clear();//清除set里所有元素}}return 0;}