当前位置:   article > 正文

C++之STL(十二)

C++之STL(十二)

1、容器适配器

  1. #include <iostream>
  2. #include <stack>
  3. #include <list>
  4. #include <queue>
  5. #include <functional>
  6. #include <iterator>
  7. using namespace std;
  8. int main() {
  9. // 栈(先进后出filo)
  10. stack<int, list<int>> s;
  11. for(int i = 0; i < 5; ++i)
  12. {
  13. s.push(i);
  14. }
  15. // 不能用下面的这种循环,因为pop后,size会发生变化,输出4 3 2
  16. // for(size_t i = 0; i < s.size(); ++i)
  17. // {
  18. // cout << s.top() << " ";
  19. // s.pop();
  20. // }
  21. while (!s.empty())
  22. {
  23. cout << s.top() << " ";
  24. s.pop();
  25. }
  26. cout << endl;
  27. // 队列(先进先出)
  28. queue<int, list<int>> q; // 注意这边的list不能用vector,因为源码中vec没有pop_front接口,所以要注意接口的匹配
  29. for (int i = 0; i < 5; ++i)
  30. {
  31. q.push(i);
  32. }
  33. while (!q.empty())
  34. {
  35. cout << q.front() << " ";
  36. q.pop();
  37. }
  38. cout << endl;
  39. // 优先级队列(不一定先进先出)
  40. int a[] = {5, 1, 3, 2, 4};
  41. priority_queue<int> pq(a, a + 5); // 这里面会调用make_heap
  42. while (!pq.empty())
  43. {
  44. cout << pq.top() << " "; // 弹出是按照值的大小,值越大,优先级越高
  45. pq.pop();
  46. }
  47. cout << endl;
  48. // 堆(二叉树,大堆或者小堆)
  49. make_heap(a, a + 5);
  50. copy(a, a + 5, ostream_iterator<int>(cout, " "));
  51. cout << endl;
  52. sort(a, a + 5, less<int>());// 默认是greater大堆
  53. copy(a, a + 5, ostream_iterator<int>(cout, " "));
  54. cout << endl;
  55. return 0;
  56. }
  57. //输出
  58. 4 3 2 1 0
  59. 0 1 2 3 4
  60. 5 4 3 2 1
  61. 5 4 3 2 1
  62. 1 2 3 4 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/772992
推荐阅读
相关标签
  

闽ICP备14008679号