自定义单调栈模板.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <stack>
  2. #include <vector>class monstk_std {
  3. public:
  4. //std::stack version
  5. //compare function : from the bottom to the top
  6. template<typename _T, typename _U>
  7. static std::vector<_T> ins(_T x, std::stack<_T>& stk, bool (*comp)(_U, _U)) {
  8. std::vector<_T> vec;
  9. while ((!stk.empty()) && (!((*comp)(stk.top(), x))))
  10. vec.push_back(stk.top()),
  11. stk.pop();
  12. stk.push(x);
  13. return vec;
  14. }
  15. //compare function : from the bottom to the top
  16. template<typename _T, typename _U>
  17. static void ins(std::vector<_T>& vec, _T x, std::stack<_T>& stk, bool (*comp)(_U, _U)) {
  18. while ((!stk.empty()) && (!((*comp)(stk.top(), x))))
  19. vec.push_back(stk.top()),
  20. stk.pop();
  21. stk.push(x);
  22. }
  23. template<typename _T>
  24. static void ext(std::vector<_T>& vec, std::stack<_T>& stk) {
  25. while (!stk.empty()) {
  26. vec.push_back(stk.top());
  27. stk.pop();
  28. }
  29. }
  30. template<typename _T>
  31. static std::vector<_T> ext(std::stack<_T>& stk) {
  32. std::vector<_T> vec;
  33. while (!stk.empty())
  34. vec.push_back(stk.top()),
  35. stk.pop();
  36. return vec;
  37. }
  38. };
  39. //-----------------------------------------------------------------------------//
  40. class monstk_pnt {
  41. //pointer(list) version
  42. //compare function : from the bottom to the top
  43. template<typename _T, typename _U>
  44. static void ins(std::vector<_T>& vec, _T x, int& siz, _T* stk, bool (*comp)(_U, _U)) {
  45. while ((siz > 0) && (!((*comp)(stk[siz], x)))) {
  46. vec.push_back(stk[siz]);
  47. siz--;
  48. }
  49. siz++;
  50. stk[siz] = x;
  51. }
  52. //compare function : from the bottom to the top
  53. template<typename _T, typename _U>
  54. staticstd::vector<_T> ins(_T x, int& siz, _T* stk, bool (*comp)(_U, _U)) {
  55. std::vector<_T> vec;
  56. while ((siz > 0) && (!((*comp)(stk[siz], x)))) {
  57. vec.push_back(stk[siz]);
  58. siz--;
  59. }
  60. siz++;
  61. stk[siz] = x;
  62. return vec;
  63. }
  64. template<typename _T>
  65. static std::vector<_T> ext(int& siz, _T* stk) {
  66. std::vector<_T> vec;
  67. while (siz > 0) {
  68. vec.push_back(stk[siz]);
  69. siz--;
  70. }
  71. return vec;
  72. }
  73. template<typename _T>
  74. static void ext(std::vector<_T>& vec, int& siz, _T* stk) {
  75. while (siz > 0) {
  76. vec.push_back(stk[siz]);
  77. siz--;
  78. }
  79. }
  80. };