• 【C++要笑着学】Functor 仿函数 | 模拟实现 stack & queue | 模拟实现优先级队列


       C++ 表情包趣味教程 👉 《C++要笑着学》

     💭 写在前面

    在上一章中,我们讲解了STL的栈和队列,本章我们来模拟实现一下它们。在讲解优先级队列的同时我们顺便把上一章提到的仿函数进行一个讲解,使用仿函数可以有效替换使用难以理解的函数指针的场景。我们通过仿函数 less 和 greater 去控制优先级队列的 Compare,从而能同时适配升序和降序。


    Ⅰ. 模拟实现 stack

    0x00 实现思路

     插入数据删除数据这些逻辑其实没有必要自己实现,而是采用转换的方式。

    两章前我们讲解了适配器的知识,这里采用的就是一些其它的适配的容器去实现。

    至于这里转换什么,我们可以进一步思考,似乎有很多容器都适合去转换,

    所以 STL 增加了一个模板参数 Container,利用 Container 来进行转换。

    在上一章的末尾,我们讲述了利用 deque 去实现栈和队列是最合适不过的了:

    template<class T, class Container = deque>

    (至于 deque 的底层我们放到后面去说,我们先学会如何用 deque 去实现栈和队列)

     对于栈而言,push 插入数据就是尾插 push_backpop 删除数据就是尾删 pop_back

    1. void push(const T& x) {
    2. _con.push_back(x); // 对于栈而言,入栈就是尾插
    3. }
    4. void pop() {
    5. _con.pop_back(); // 对于栈而言,出栈就是尾删
    6. }

    返回堆顶数据我们可以用 back(),即可达到返回尾上数据的效果,本质上是一种封装。

    1. const T& top() {
    2. return _con.back(); // 返回尾上数据
    3. }

     这里甚至都不需要考虑断言,因为那是下层需要做的事情,这里我们要做的只是 "转换" 。

    💬 代码:stack

    1. #include
    2. #include
    3. using namespace std;
    4. namespace foxny {
    5. template<class T, class Container = deque>
    6. class stack {
    7. public:
    8. void push(const T& x) {
    9. _con.push_back(x); // 对于栈而言,入栈就是尾插
    10. }
    11. void pop() {
    12. _con.pop_back(); // 对于栈而言,出栈就是尾删
    13. }
    14. const T& top() {
    15. return _con.back(); // 返回尾上数据
    16. }
    17. size_t size() {
    18. return _con.size(); // 返回大小
    19. }
    20. bool empty() {
    21. return _con.empty(); // 返回是否为空
    22. }
    23. private:
    24. Container _con;
    25. };
    26. }

    0x01 代码测试

     先默认用 deque 去存储:

    1. #include
    2. #include
    3. using namespace std;
    4. namespace foxny {
    5. void test_stack1() {
    6. stack<int> st;
    7. st.push(1);
    8. st.push(2);
    9. st.push(3);
    10. st.push(4);
    11. while (!st.empty()) {
    12. cout << st.top() << " ";
    13. st.pop();
    14. }
    15. cout << endl;
    16. }
    17. }

    🚩 运行结果:

     默认传 deque,如果不想用 deque,你可以自由的去传。

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. namespace foxny {
    6. void test_stack2() {
    7. stack<int, vector<int>> st; // 我想默认用 vector
    8. st.push(1);
    9. st.push(2);
    10. st.push(3);
    11. st.push(4);
    12. while (!st.empty()) {
    13. cout << st.top() << " ";
    14. st.pop();
    15. }
    16. cout << endl;
    17. }
    18. }

    🚩 运行结果:

     我们再试试默认用 list 可不可以:

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. namespace foxny {
    6. void test_stack3() {
    7. stack<int, list<int>> st; // 我想默认用 list
    8. st.push(1);
    9. st.push(2);
    10. st.push(3);
    11. st.push(4);
    12. while (!st.empty()) {
    13. cout << st.top() << " ";
    14. st.pop();
    15. }
    16. cout << endl;
    17. }
    18. }

    🚩 运行结果:

    ❓ 思考:可否用 string

    勉强可以,只要你是顺序容器都可以。但是用 string 是有风险的,可能会出现溢出和截断。

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. namespace foxny {
    6. void test_stack4() {
    7. stack<int, string> st; // 我想默认用 string
    8. st.push(1);
    9. st.push(2);
    10. st.push(3);
    11. st.push(400); // 这里推一个400看看
    12. while (!st.empty()) {
    13. cout << st.top() << " ";
    14. st.pop();
    15. }
    16. cout << endl;
    17. }
    18. }

    🚩 运行结果:

    🔺 总结:从上层角度来看,其默认是一个双端队列,我底层用什么存,去实现这个栈并不重要,只要其符合要求就行。它保存的是栈的性质,复用的是容器的代码。

    Ⅱ. 模拟实现 queue

    0x00 实现思路

     一回生二回熟,其默认容器也是 deque,直接照着 stack 的基础去修改成 queue 即可。

    template<class T, class Container = deque>

    queue 是先进先出的,queuepush 仍然是尾部的插入,而 pop 需要支持头部的删除。

    1. void push(const T& x) {
    2. _con.push_back(x); // 进队
    3. }
    4. void pop() {
    5. _con.pop_front(); // 出队
    6. }

    值得注意的是,queue 不能用 vector 去适配,因为 vector 压根就没有 pop_front 这个接口。

     (我看你是在刁难我胖虎.jpg)

    queue front back 我们直接调 front back 去取队列头尾的数据即可:

    1. const T& front() {
    2. return _con.front();
    3. }
    4. const T& back() {
    5. return _con.back();
    6. }

     剩下的 sizeempty 都不用变。

    💬 代码实现:queue

    1. #include
    2. #include
    3. using namespace std;
    4. namespace foxny {
    5. template<class T, class Container = deque>
    6. class queue {
    7. public:
    8. void push(const T& x) {
    9. _con.push_back(x);
    10. }
    11. void pop() {
    12. _con.pop_front();
    13. }
    14. const T& front() {
    15. return _con.front();
    16. }
    17. const T& back() {
    18. return _con.back();
    19. }
    20. size_t size() {
    21. return _con.size();
    22. }
    23. bool empty() {
    24. return _con.empty();
    25. }
    26. private:
    27. Container _con;
    28. };
    29. }

    0x01 代码测试

     先测试默认用 deque 去存储:

    1. #include
    2. #include
    3. using namespace std;
    4. namespace foxny {
    5. void test_queue1() {
    6. queue<int> q;
    7. q.push(1);
    8. q.push(2);
    9. q.push(3);
    10. q.push(4);
    11. while (!q.empty()) {
    12. cout << q.front() << " ";
    13. q.pop();
    14. }
    15. cout << endl;
    16. }
    17. }

    🚩 运行结果:

    指定用 list 去存:

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. namespace foxny {
    6. void test_queue2() {
    7. queue<int, list<int>> q;
    8. q.push(1);
    9. q.push(2);
    10. q.push(3);
    11. q.push(4);
    12. while (!q.empty()) {
    13. cout << q.front() << " ";
    14. q.pop();
    15. }
    16. cout << endl;
    17. }
    18. }

    🚩 运行结果:

    我们来试一下指定用 vector 会怎么样:

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. namespace foxny {
    6. void test_queue3() {
    7. queue<int, vector<int>> q;
    8. q.push(1);
    9. q.push(2);
    10. q.push(3);
    11. q.push(4);
    12. while (!q.empty()) {
    13. cout << q.front() << " ";
    14. q.pop();
    15. }
    16. cout << endl;
    17. }
    18. }

    🚩 运行结果:

    error C2039: "pop_front": 不是 "std::vector>" 的成员
    1>        with
    1>        [
    1>            T=int
    1>        ]
    1>D:\360MoveData\Users\Chaos\Desktop\code2022\2022_7_17\2022_7_17\test.cpp(62): message : 参见“std::vector>”的声明
    1>        with
    1>        [
    1>            T=int
    1>        ]
    1>D:\360MoveData\Users\Chaos\Desktop\code2022\2022_7_17\2022_7_17\test.cpp(14): message : 在编译 类 模板 成员函数“void foxny::queue>>::pop(void)”时……

     正所谓 —— 明知山有虎,别去明知山。明知 vector 无头删,队列就别用 vector!

    用其他东西转换搞出来的栈和队列,只要符合要求就可以。实际上也不一定真的是直接转换。

     我们下面还要学一个更复杂的

    Ⅲ. 模拟实现 priority_queue

    0x00 基本实现思路

     据我所知,在优先级队列中,插入数据和删除数据的时间复杂度为 O(logN) 。

    默认情况下的优先级队列是大堆,我们先不考虑用仿函数去实现兼容大堆小队排列问题,

    我们先去实现大堆,先把基本的功能实现好,带着讲解完仿函数后再去进行优化实现。

     优先级队列相较于普通的队列,其区别主要是在 push pop 上,

    即需要在插入 / 删除数据的同时,增添调整的功能,并且 STL 的优先级队列是由堆来维护的:

    1. void push(const T& x) {
    2. _con.push_back(x);
    3. AdjustUp(_con.size() - 1);
    4. }

     入队时将数据推入后,从最后一个元素开始进行上调。

    出队时采用堆的删除手法,将根元素(即队头)和最后一个元素进行交换,并调用尾删掉队头。

    既然用了头尾交换法,我们就不得不对队列重新调整,所以从根位置进行下调,即可完成出队。

    1. void pop() {
    2. assert(!_con.empty());
    3. swap(_con[0], _con[_con.size() - 1]);
    4. _con.pop_back();
    5. AdjustDown(0);
    6. }

    既然需要上调和下调操作,我们不可避免地需要实现上调和下调的算法。

    我们这里暂时写死,设计成大堆的 AdjustUp AdjustDown

    1. /* 向上调整算法 */
    2. void AdjustUp(size_t child) {
    3. size_t father = (child - 1) / 2;
    4. while (child > 0) {
    5. if (_con[father] < _con[child]) {
    6. swap(_con[father], _con[child]);
    7. child = father;
    8. father = (child - 1) / 2;
    9. }
    10. else {
    11. break;
    12. }
    13. }
    14. }
    15. /* 向下调整算法 */
    16. void AdjustDown(size_t father) {
    17. size_t child = father * 2 + 1; // 默认认为左孩子大
    18. while (child < _con.size()) {
    19. // 判断右孩子是否存在,并且是否比左孩子大?
    20. if (child + 1 < _con.size() && _con[child] < _con[child + 1]) {
    21. child += 1;
    22. }
    23. if (_con[father] < _con[child]) {
    24. swap(_con[father], _con[child]);
    25. father = child;
    26. child = father * 2 + 1;
    27. }
    28. else {
    29. break;
    30. }
    31. }
    32. }

    这里我就不重复讲解了,如果你对这一块知识比较生疏,建议复习一下数据结构的堆。

    🔗 链接:【数据结构】堆的概念 | 从零开始实现数组堆

    向上调整算法和向下调整算法实现完后,我们把剩下的可以直接用 _con 转换的接口实现一下:

    1. const T& top() {
    2. return _con[0];
    3. }
    4. size_t size() {
    5. return _con.size();
    6. }
    7. bool empty() {
    8. return _con.empty();
    9. }

    很简单,不过值得注意的是,返回堆顶数据的 top 接口,我们用了 const 引用返回。

    ❓ 思考:为什么这里要用引用?为什么还要加个 const

    ① 考虑到如果这里 T string,甚至是更大的对象,传值返回就有一次拷贝构造,代价就大了。

    ② 如果能让你随随便便修改我堆顶的数据,那岂不是  显得我很随便?   很危险?

    0x01 写死了的大堆优先级队列

    💬 代码:写死了的大堆优先级队列 demo

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. namespace foxny {
    6. template<class T, class Container = vector>
    7. class priority_queue {
    8. public:
    9. /* 向上调整算法 */
    10. void AdjustUp(size_t child) {
    11. size_t father = (child - 1) / 2;
    12. while (child > 0) {
    13. if (_con[father] < _con[child]) {
    14. swap(_con[father], _con[child]);
    15. child = father;
    16. father = (child - 1) / 2;
    17. }
    18. else {
    19. break;
    20. }
    21. }
    22. }
    23. /* 向下调整算法 */
    24. void AdjustDown(size_t father) {
    25. size_t child = father * 2 + 1; // 默认认为左孩子大
    26. while (child < _con.size()) {
    27. // 判断右孩子是否存在,并且是否比左孩子大?
    28. if (child + 1 < _con.size() && _con[child] < _con[child + 1]) {
    29. child += 1;
    30. }
    31. if (_con[father] < _con[child]) {
    32. swap(_con[father], _con[child]);
    33. father = child;
    34. child = father * 2 + 1;
    35. }
    36. else {
    37. break;
    38. }
    39. }
    40. }
    41. /* 入数据 */
    42. void push(const T& x) {
    43. _con.push_back(x);
    44. AdjustUp(_con.size() - 1);
    45. }
    46. /* 出数据 */
    47. void pop() {
    48. assert(!_con.empty());
    49. swap(_con[0], _con[_con.size() - 1]);
    50. _con.pop_back();
    51. AdjustDown(0);
    52. }
    53. /* 返回堆顶数据 */
    54. const T& top() {
    55. return _con[0];
    56. }
    57. /* 返回大小 */
    58. size_t size() {
    59. return _con.size();
    60. }
    61. /* 判断是否为空 */
    62. bool empty() {
    63. return _con.empty();
    64. }
    65. private:
    66. Container _con;
    67. };
    68. }

    💬 测试:目前我们是写死了的大堆,还没有加入仿函数,我们先跑一下看看

    1. void test_priority_queue1() {
    2. priority_queue<int> pQ;
    3. pQ.push(2);
    4. pQ.push(5);
    5. pQ.push(1);
    6. pQ.push(6);
    7. pQ.push(8);
    8. while (!pQ.empty()) {
    9. cout << pQ.top() << " ";
    10. pQ.pop();
    11. }
    12. cout << endl;
    13. }

    🚩 运行结果:

     我们写死的最大问题是 —— 如果想按升序排列,就没办法排了。

    我们这里写的用来排降序的大堆,如果想排升序我们需要写小堆,

    C++ 在这里有一种叫仿函数的东西,可以控制这些东西,我们下面先来介绍一下仿函数。

    0x02 仿函数(functor)

    📚 概念:使一个类的使用看上去像一个函数。可以像函数一样使用的对象,称为函数对象。

    其实现就是在类中重载 operator(),使得该类具备类似函数的行为,就是一个仿函数类了。

    C语言优先级,() 圆括号使用形式为 表达式 或 "作为函数形参列表的括号" 

    我们这里重载的其实就是:函数名(形参表)

    💬 代码:我们来写一个最简单的仿函数

    1. namespace foxny {
    2. struct less {
    3. // 仿函数(函数对象)———— 对象可以像调用函数一样去使用
    4. bool operator()(int x, int y) {
    5. return x < y;
    6. }
    7. };
    8. void test_functor() {
    9. less lessCmp; // 定义一个对象(这里我用小驼峰,能看上去更像函数)
    10. cout << lessCmp(10, 20) << endl; // 是对象,但是却能像函数一样去使用
    11. }
    12. }

    🚩 运行结果:1

    这里定义对象的时候我用的我是小驼峰,这样看上去更像是一个函数了,以假乱真。

    我们定义的 lessCmp 是一个对象,但是我们却可以像使用函数一样给它传递参数:

    lessCmp(10, 20);

    ohhhhhhhhhhhhhhhh!!!

     我们还可以使其能够支持泛型,我们加一个 template 模板:

    1. // 支持泛型
    2. template<class T> struct less {
    3. bool operator()(const T& x, const T& y) const {
    4. return x < y;
    5. }
    6. };
    7. void test_functor() {
    8. less<int> lessCmp;
    9. cout << lessCmp(10, 20) << endl;
    10. }

    less 是用来比较谁小的,对应的,我们再实现一个比较谁大的 greater

    1. // less: 小于的比较
    2. template<class T> struct less {
    3. bool operator()(const T& x, const T& y) const {
    4. return x < y;
    5. }
    6. };
    7. // greater: 大于的比较
    8. template<class T> struct greater {
    9. bool operator()(const T& x, const T& y) const {
    10. return x > y;
    11. }
    12. };
    13. void test_functor() {
    14. less<int> lessCmp;
    15. cout << lessCmp(10, 20) << endl;
    16. greater<int> GreaterCmp;
    17. cout << GreaterCmp(10, 20) << endl;
    18. }

    🚩 运行结果:1   0

    一个对象能像函数一样用,看上去很神奇,实际上调用的只是我们重载的 operator() 而已。

    这些操作都是归功于运算符重载功能,这就是仿函数!

    ❓ 思考:我们在C阶段不是学过函数指针么,用函数指针不香吗?

    函数指针确实可以做到这些功能。但是在这里函数指针跟仿函数比,一点都不香。

     反而很臭!啊,啊,啊♂ 啊♂ 啊♂ 啊啊啊!!!

    在 C++ 里其实是非常鄙夷使用函数指针的,函数的指针在一些地方用起来非常复杂。

    1. static void( * set_malloc_handler(void (*f)()))() {
    2. void (* old)() = __malloc_alloc_oom_handler;
    3. __malloc_alloc_oom_handler = f;
    4. return(old);
    5. }

    这个函数的参数是什么?函数的返回值是什么?

    这就很阴间了,这就是函数指针的杰作…… 所以 C++ 搞出了仿函数,简化了好多点。

    📚 仿函数的优势:很多场景,替换了函数指针。

    0x03 加了仿函数后的优先级队列

     我们现在用仿函数去比较那些数据,这样就不会写死了。

    💬 代码:priority_queue

    1. #include
    2. #include
    3. #include // 这里放的是一些仿函数
    4. #include
    5. using namespace std;
    6. namespace foxny {
    7. // less: 小于的比较
    8. template<class T>
    9. struct less {
    10. bool operator()(const T& x, const T& y) const {
    11. return x < y;
    12. }
    13. };
    14. // greater: 大于的比较
    15. template<class T>
    16. struct greater {
    17. bool operator()(const T& x, const T& y) const {
    18. return x > y;
    19. }
    20. };
    21. template<class T, class Container = vector, class Compare = less>
    22. class priority_queue {
    23. public:
    24. /* 向上调整算法 */
    25. void AdjustUp(size_t child) {
    26. Compare cmpFunc;
    27. size_t father = (child - 1) / 2;
    28. while (child > 0) {
    29. // if (_con[father] < _con[child]) {
    30. if (cmpFunc(_con[father], _con[child])) {
    31. swap(_con[father], _con[child]);
    32. child = father;
    33. father = (child - 1) / 2;
    34. }
    35. else {
    36. break;
    37. }
    38. }
    39. }
    40. /* 向下调整算法 */
    41. void AdjustDown(size_t father) {
    42. Compare cmpFunc;
    43. size_t child = father * 2 + 1; // 默认认为左孩子大
    44. while (child < _con.size()) {
    45. // if (child + 1 < _con.size() && _con[child] < _con[child + 1]) {
    46. if (child + 1 < _con.size() && cmpFunc(_con[child], _con[child + 1])) {
    47. child += 1;
    48. }
    49. // if (_con[father] < _con[child]) {
    50. if (cmpFunc(_con[father], _con[child])) {
    51. swap(_con[father], _con[child]);
    52. father = child;
    53. child = father * 2 + 1;
    54. }
    55. else {
    56. break;
    57. }
    58. }
    59. }
    60. /* 入数据 */
    61. void push(const T& x) {
    62. _con.push_back(x);
    63. AdjustUp(_con.size() - 1);
    64. }
    65. /* 出数据 */
    66. void pop() {
    67. assert(!_con.empty());
    68. swap(_con[0], _con[_con.size() - 1]);
    69. _con.pop_back();
    70. AdjustDown(0);
    71. }
    72. /* 返回堆顶数据 */
    73. const T& top() {
    74. return _con[0];
    75. }
    76. /* 返回大小 */
    77. size_t size() {
    78. return _con.size();
    79. }
    80. /* 判断是否为空 */
    81. bool empty() {
    82. return _con.empty();
    83. }
    84. private:
    85. Container _con;
    86. };
    87. }

    💭 测试:我们来测试一下效果如何:

    1. // 大于比较,搞小堆
    2. void test_priority_queue2() {
    3. priority_queue<int, vector<int>, greater<int>> pQ;
    4. pQ.push(2);
    5. pQ.push(5);
    6. pQ.push(1);
    7. pQ.push(6);
    8. pQ.push(8);
    9. while (!pQ.empty()) {
    10. cout << pQ.top() << " ";
    11. pQ.pop();
    12. }
    13. cout << endl;
    14. }

    🚩 运行结果:1 2 4 6 8

    1. // 小于比较,搞大堆
    2. void test_priority_queue1() {
    3. priority_queue<int> pQ;
    4. pQ.push(2);
    5. pQ.push(5);
    6. pQ.push(1);
    7. pQ.push(6);
    8. pQ.push(8);
    9. while (!pQ.empty()) {
    10. cout << pQ.top() << " ";
    11. pQ.pop();
    12. }
    13. cout << endl;
    14. }

    🚩 运行结果:8 6 5 2 1

     这里的仿函数在编译器视角是这样的:

    1. if (cmpFunc(_con[father], _con[child]))
    2. 👇
    3. if (cmpFunc.operator()(_con[father], _con[child]))
    4. 👇
    5. // 以 less 为例
    6. template<class T>
    7. struct less {
    8. bool operator()(const T& x, const T& y) const {
    9. return x < y;
    10. }
    11. };
    12. 最后返回 _con[father] < _con[child] ,true 还是 false

    0x04 迭代器的实现

    1. // 创造空的优先级队列
    2. priority_queue()
    3. : _con()
    4. {}
    5. // 迭代器
    6. template<class InputIterator>
    7. priority_queue (InputIterator first, InputIterator last)
    8. : _con(first, last)
    9. {
    10. while (first != last) {
    11. _con.push_back(*first++);
    12. }
    13. for (int father = (_con.size()-1-1) / 2; father >= 0; father++) {
    14. AdjustDown(father);
    15. }
    16. }

     我们就可以拿这个来解决一些问题,比如:

    1. void test_priority_queue3() {
    2. // TOP K
    3. int arr[] = {1,4,2,7,8,9};
    4. priority_queue<int> pQ(arr, arr + 6); // 传一个迭代器区间
    5. }

    Ⅳ. 完整代码

    0x00 stack

    1. #include
    2. #include // 做Container
    3. #include // 测试用
    4. #include // 测试用
    5. using namespace std;
    6. namespace foxny {
    7. template<class T, class Container = deque>
    8. class stack {
    9. public:
    10. void push(const T& x) {
    11. _con.push_back(x); // 对于栈而言,入栈就是尾插
    12. }
    13. void pop() {
    14. _con.pop_back(); // 对于栈而言,出栈就是尾删
    15. }
    16. const T& top() {
    17. return _con.back(); // 返回尾上数据
    18. }
    19. size_t size() {
    20. return _con.size(); // 返回大小
    21. }
    22. bool empty() {
    23. return _con.empty(); // 返回是否为空
    24. }
    25. private:
    26. Container _con;
    27. };
    28. void test_stack1() {
    29. stack<int> st;
    30. st.push(1);
    31. st.push(2);
    32. st.push(3);
    33. st.push(4);
    34. while (!st.empty()) {
    35. cout << st.top() << " ";
    36. st.pop();
    37. }
    38. cout << endl;
    39. }
    40. void test_stack2() {
    41. stack<int, vector<int>> st; // 我想默认用 vector
    42. st.push(1);
    43. st.push(2);
    44. st.push(3);
    45. st.push(4);
    46. while (!st.empty()) {
    47. cout << st.top() << " ";
    48. st.pop();
    49. }
    50. cout << endl;
    51. }
    52. void test_stack3() {
    53. stack<int, list<int>> st; // 我想默认用 list
    54. st.push(1);
    55. st.push(2);
    56. st.push(3);
    57. st.push(4);
    58. while (!st.empty()) {
    59. cout << st.top() << " ";
    60. st.pop();
    61. }
    62. cout << endl;
    63. }
    64. }
    65. int main(void)
    66. {
    67. foxny::test_stack1();
    68. foxny::test_stack2();
    69. foxny::test_stack3();
    70. return 0;
    71. }

    0x01 queue

    1. #include
    2. #include // 做Container
    3. #include // 测试用
    4. using namespace std;
    5. namespace foxny {
    6. template<class T, class Container = deque>
    7. class queue {
    8. public:
    9. void push(const T& x) {
    10. _con.push_back(x);
    11. }
    12. void pop() {
    13. _con.pop_front();
    14. }
    15. const T& front() {
    16. return _con.front();
    17. }
    18. const T& back() {
    19. return _con.back();
    20. }
    21. size_t size() {
    22. return _con.size();
    23. }
    24. bool empty() {
    25. return _con.empty();
    26. }
    27. private:
    28. Container _con;
    29. };
    30. void test_queue1() {
    31. queue<int> q;
    32. q.push(1);
    33. q.push(2);
    34. q.push(3);
    35. q.push(4);
    36. while (!q.empty()) {
    37. cout << q.front() << " ";
    38. q.pop();
    39. }
    40. cout << endl;
    41. }
    42. void test_queue2() {
    43. queue<int, list<int>> q;
    44. q.push(1);
    45. q.push(2);
    46. q.push(3);
    47. q.push(4);
    48. while (!q.empty()) {
    49. cout << q.front() << " ";
    50. q.pop();
    51. }
    52. cout << endl;
    53. }
    54. }
    55. int main(void)
    56. {
    57. foxny::test_queue1();
    58. foxny::test_queue2();
    59. return 0;
    60. }

    0x02 priority_queue

    1. #include
    2. #include
    3. #include // 这里放的是一些仿函数
    4. #include
    5. using namespace std;
    6. namespace foxny {
    7. // less: 小于的比较
    8. template<class T>
    9. struct less {
    10. bool operator()(const T& x, const T& y) const {
    11. return x < y;
    12. }
    13. };
    14. // greater: 大于的比较
    15. template<class T>
    16. struct greater {
    17. bool operator()(const T& x, const T& y) const {
    18. return x > y;
    19. }
    20. };
    21. template<class T, class Container = vector, class Compare = less>
    22. class priority_queue {
    23. Compare _cmpFunc;
    24. public:
    25. // 创造空的优先级队列
    26. priority_queue()
    27. : _con()
    28. {}
    29. // 迭代器
    30. template<class InputIterator>
    31. priority_queue (InputIterator first, InputIterator last)
    32. : _con(first, last)
    33. {
    34. int count = _con.size();
    35. int root = ((count - 2) >> 1);
    36. for (; root >= 0; root--) {
    37. AdjustDown(root);
    38. }
    39. }
    40. /* 向上调整算法 */
    41. void AdjustUp(size_t child) {
    42. Compare cmpFunc;
    43. size_t father = (child - 1) / 2;
    44. while (child > 0) {
    45. // if (_con[father] < _con[child]) {
    46. if (cmpFunc(_con[father], _con[child])) {
    47. swap(_con[father], _con[child]);
    48. child = father;
    49. father = (child - 1) / 2;
    50. }
    51. else {
    52. break;
    53. }
    54. }
    55. }
    56. /* 向下调整算法 */
    57. void AdjustDown(size_t father) {
    58. Compare cmpFunc;
    59. size_t child = father * 2 + 1; // 默认认为左孩子大
    60. while (child < _con.size()) {
    61. // if (child + 1 < _con.size() && _con[child] < _con[child + 1]) {
    62. if (child + 1 < _con.size() && cmpFunc(_con[child], _con[child + 1])) {
    63. child += 1;
    64. }
    65. // if (_con[father] < _con[child]) {
    66. if (cmpFunc(_con[father], _con[child])) {
    67. swap(_con[father], _con[child]);
    68. father = child;
    69. child = father * 2 + 1;
    70. }
    71. else {
    72. break;
    73. }
    74. }
    75. }
    76. /* 入数据 */
    77. void push(const T& x) {
    78. _con.push_back(x);
    79. AdjustUp(_con.size() - 1);
    80. }
    81. /* 出数据 */
    82. void pop() {
    83. assert(!_con.empty());
    84. swap(_con[0], _con[_con.size() - 1]);
    85. _con.pop_back();
    86. AdjustDown(0);
    87. }
    88. /* 返回堆顶数据 */
    89. const T& top() {
    90. return _con[0];
    91. }
    92. /* 返回大小 */
    93. size_t size() {
    94. return _con.size();
    95. }
    96. /* 判断是否为空 */
    97. bool empty() {
    98. return _con.empty();
    99. }
    100. private:
    101. Container _con;
    102. };
    103. // 小于比较,搞大堆
    104. void test_priority_queue1() {
    105. priority_queue<int> pQ;
    106. pQ.push(2);
    107. pQ.push(5);
    108. pQ.push(1);
    109. pQ.push(6);
    110. pQ.push(8);
    111. while (!pQ.empty()) {
    112. cout << pQ.top() << " ";
    113. pQ.pop();
    114. }
    115. cout << endl;
    116. }
    117. // 大于比较,搞小堆
    118. void test_priority_queue2() {
    119. priority_queue<int, vector<int>, greater<int>> pQ;
    120. pQ.push(2);
    121. pQ.push(5);
    122. pQ.push(1);
    123. pQ.push(6);
    124. pQ.push(8);
    125. while (!pQ.empty()) {
    126. cout << pQ.top() << " ";
    127. pQ.pop();
    128. }
    129. cout << endl;
    130. }
    131. }
    132. int main(void)
    133. {
    134. foxny::test_priority_queue1();
    135. foxny::test_priority_queue2();
    136. return 0;
    137. }

    1. 📌 [ 笔者 ]   王亦优
    2. 📃 [ 更新 ]   2022.7.26
    3. ❌ [ 勘误 ]   /* 暂无 */
    4. 📜 [ 声明 ]   由于作者水平有限,本文有错误和不准确之处在所难免,
    5. 本人也很想知道这些错误,恳望读者批评指正!

    📜 参考资料 

    C++reference[EB/OL]. []. http://www.cplusplus.com/reference/.

    Microsoft. MSDN(Microsoft Developer Network)[EB/OL]. []. .

    百度百科[EB/OL]. []. https://baike.baidu.com/.

    比特科技. C++[EB/OL]. 2021[2021.8.31]. 

  • 相关阅读:
    vue3 组件v-model绑定props里的值,修改组件的值要触发回调
    自学软件测试,学到什么程度可以出去找工作啊?
    HTTP 原理
    《六月集训》(第二十四天)——线段树
    07 nginx 的 worker process 的调试
    案例复现,带你分析Priority Blocking Queue比较器异常导致的NPE问题
    springboot整合redis
    泄露35TB数据,医疗巨头Henry Schein遭受黑猫勒索组织攻击
    基于Matlab实现图像分割技术(附上源码+图像)
    day05-SpringBootWeb请求响应
  • 原文地址:https://blog.csdn.net/weixin_50502862/article/details/125826454