C++set集合

set集合容器:

调用头文件:

  1. #include<set>
  2. using namespace std;

详细用法(部分):

  • set<int> t      ------      定义一个int类型的容器,(默认)里面元素从小到大
  • set<int, greater<int> > t      ------      定义一个int类型的容器,里面元素从大到小
  • t.insert(k)      ------      插入元素k,多次插入同一个元素后面无效
  • t.count(k)      ------      判断元素k是否在容器内
  • t.erase(k)      ------      删除元素k,若不存在则删除无效
  • t.clear()      ------      清空容器
  • t.size()      ------      返回容器现有元素个数
  • t.empty()      ------      判断容器是否为空

 

想遍历set里的元素或进行进一步修改,必须定义对应迭代器,以下三种定义方法(迭代器类似于指针)

  • set<int>::iterator it      ------      定义正向迭代器
  • set<int>::reverse_iterator rit;      ------      定义反向迭代器
  • auto it = t.begin();      ------      因t.begin()返回正向迭代器,所以it自动被定义为正向迭代器,可适应其他所有操作

 

 

以下需要迭代器的操作:

  • t.begin()      ------      返回set中第一个元素,类型为正向迭代器
  • t.rbegin()      ------      返回set中最后一个元素的后面一个位置,类型为反向迭代器
  • t.end()      ------      返回set中最后一个元素,类型为正向迭代器
  • t.rend()      ------      返回set中第一个元素,类型为反向迭代器
  • t.find(k)      ------      寻找k,若找到返回对应的迭代器,否则返回end();
  • t.insert(a, b)      ------      插入指针[a, b)之间的元素,已有元素不会再次插入
  • t.erase(it)      ------      删除迭代器it对应的元素
  • t.erase(l, r)      ------      删除迭代器[l, r)之间的元素
  • lower_bound(k)      ------      返回第一个大于等于k的元素的迭代器
  • upper_bound(k)      ------      返回第一个大于k的元素的迭代器

 

 

  1. #include<stdio.h>
  2. #include<set>
  3. using namespace std;
  4. set<int> t;
  5. int main(void)
  6. {
  7. t.insert(5);
  8. t.insert(3);
  9. t.insert(8);
  10. t.insert(9);
  11. t.insert(12);
  12. printf("the size is %d\n", t.size());
  13. printf("%d %d\n", t.count(5), t.count(-1)); //运行结果:1 0
  14. set<int>::iterator it;
  15. for(it=t.begin();it!=t.end();it++) //运行结果:3 5 8 9 12
  16. printf("%d ", *it);
  17. printf("\n");
  18. set<int>::reverse_iterator rit;
  19. for(rit=t.rbegin();rit!=t.rend();rit++) //运行结果:12 9 8 5 3
  20. printf("%d ", *rit);
  21. printf("\n");
  22. auto a = t.begin();
  23. auto b = t.begin();
  24. b++;
  25. t.erase(a,b);
  26. for(it=t.begin();it!=t.end();it++) //运行结果:5 8 9 12
  27. printf("%d ", *it);
  28. printf("\n");
  29. a = t.lower_bound(6);
  30. b = t.upper_bound(8);
  31. printf("%d %d\n", *a, *b); //运行结果:8 9
  32. return 0;
  33. }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章