fork download
  1. #include <cassert>
  2. #include <cstddef>
  3. #include <utility>
  4.  
  5. template <typename K, typename V>
  6. struct key_value_pair {
  7. using key_type = K;
  8. using value_type = V;
  9.  
  10. key_value_pair() = default;
  11. key_value_pair(const key_value_pair& other) = default;
  12. key_value_pair(key_value_pair&& other) noexcept = default;
  13. key_value_pair(const key_type& key, const value_type& value)
  14. : key_(key),
  15. value_(value)
  16. {}
  17. key_value_pair(key_type&& key, value_type&& value) noexcept
  18. : key_(std::move(key)),
  19. value_(std::move(value))
  20. {}
  21. key_value_pair& operator =(key_value_pair&& other) noexcept = default;
  22. key_value_pair& operator =(const key_value_pair& other)
  23. {
  24. return *this = key_value_pair(other);
  25. }
  26.  
  27. private:
  28. key_type key_;
  29. value_type value_;
  30. };
  31.  
  32. template <typename K, typename V, std::size_t N = 5>
  33. class key_value_pair_stack {
  34. public:
  35. using element_type = key_value_pair<K, V>;
  36.  
  37. public:
  38. key_value_pair_stack() : data_(), i_(0)
  39. {
  40. }
  41.  
  42. void push(const element_type& obj)
  43. {
  44. this->push(element_type(obj));
  45. }
  46.  
  47. void push(element_type&& obj)
  48. {
  49. assert(i_ < N);
  50. data_[i_++] = std::move(obj);
  51. }
  52.  
  53. void push(
  54. const typename element_type::key_type& key,
  55. const typename element_type::value_type& value)
  56. {
  57. this->push(value_type(key, value));
  58. }
  59.  
  60. void push(
  61. typename element_type::key_type&& key,
  62. typename element_type::value_type&& value)
  63. {
  64. this->push(element_type(std::move(key), std::move(value)));
  65. }
  66.  
  67. element_type pop()
  68. {
  69. assert(i_ > 0);
  70. return data_[--i_];
  71. }
  72.  
  73. constexpr std::size_t max_size() const
  74. {
  75. return N;
  76. }
  77.  
  78. std::size_t size() const
  79. {
  80. return i_;
  81. }
  82.  
  83. void clear()
  84. {
  85. i_ = 0;
  86. }
  87.  
  88. private:
  89. element_type data_[N];
  90. std::size_t i_;
  91. };
  92.  
  93. int main() {
  94. key_value_pair_stack<int, double> s;
  95. s.push(5, 10.);
  96. s.push(4, 10.);
  97. const auto t0 = s.pop(); //(4, 10.)
  98. const auto t1 = s.pop(); //(5, 10.)
  99.  
  100. return 0;
  101. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty