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

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