[关闭]
@lychee123 2017-10-02T13:44:32.000000Z 字数 1415 阅读 900

Power OJ-2340: SB_cyh and his BST one(set)

STL


  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6. int main()
  7. {
  8. int x;
  9. char a[22];
  10. set<int>s;//定义int型集合s。(set可以是任何类型)往set里丢的数如果有相同的会保留一个,如果允许有相同的数,那么使用multiset.往set里丢的数默认从小到大排序的
  11. set<int>::iterator it;//迭代器it相当于一个指针
  12. while(~scanf("%s",a))
  13. {
  14. if(a[0]=='-')
  15. break;
  16. if(a[0]=='i')
  17. {
  18. scanf("%d",&x);
  19. s.insert(x);//insert()函数,代表插入某个数,如果该数已存在,忽略这一操作
  20. }
  21. if(a[0]=='d')
  22. {
  23. scanf("%d",&x);
  24. if(s.count(x)==0)//对x计数,如果个数为零表示未查找到
  25. printf("Input Error\n");
  26. else
  27. s.erase(x);//erase()函数是删除函数
  28. }
  29. if(a[0]=='s')
  30. {
  31. scanf("%d",&x);
  32. it=s.find(x);//查找x的地址附给指针it
  33. if(s.count(x)==0)
  34. printf("Input Error\n");
  35. else
  36. {
  37. it++;
  38. if(it==s.end())//set里最后一位的下一为s.end()
  39. printf("%d is the maximum\n",x);
  40. else
  41. {
  42. it=s.upper_bound(x);//s.upper_bound(x)返回大于x元素且与x最接近的数的迭代器
  43. printf("The successor of %d is %d\n",x,*it);
  44. }
  45. }
  46. }
  47. if(a[0]=='p'&&a[2]=='e')
  48. {
  49. scanf("%d",&x);
  50. it=s.find(x);
  51. if(s.count(x)==0)
  52. printf("Input Error\n");
  53. else
  54. {
  55. if(it==s.begin())
  56. printf("%d is the minimum\n",x);
  57. else
  58. {
  59. it=s.lower_bound(x);//返回指向大于(或等于)某值的第一个元素的迭代器
  60. it--;//由于该数x在set里存在所以it指向的为该数x
  61. printf("The predecessor of %d is %d\n",x,*it);
  62. }
  63. }
  64. }
  65. if(a[0]=='p'&&a[2]=='i')
  66. {
  67. for(it=s.begin();it!=s.end();it++)//*s.begin()等于set里的第一个数,*s.end()==s.size()集合中元素的数目;
  68. printf("%d,",*it);//it是指针*it表示指针指向的数
  69. printf("end of print\n");
  70. }
  71. if(a[0]=='e')
  72. {
  73. printf("end of this test\n");
  74. s.clear();//清除set里所有元素
  75. }
  76. }
  77. return 0;
  78. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注