multiset.h 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #include <set>
  2. template<
  3. class Key,
  4. class Compare = std::less<Key>,
  5. class Allocator = std::allocator<Key>
  6. > class multiset : public std::multiset<Key, Compare, Allocator>
  7. {
  8. typedef multiset<Key, Compare, Allocator> self;
  9. typedef std::multiset<Key, Compare, Allocator> parent;
  10. public:
  11. typedef typename parent::iterator iterator;
  12. typedef typename parent::const_iterator const_iterator;
  13. // returns iterator poiting to first element equal to key.
  14. const_iterator equal( const Key& key ) const
  15. {
  16. const_iterator eq = self::lower_bound(key);
  17. if(eq == self::end() || *eq != key) {
  18. return self::end();
  19. } else {
  20. return eq;
  21. }
  22. }
  23. // returns iterator poiting to first element equal to key.
  24. // if no such element exists, return iterator pointing to last element less than key.
  25. const_iterator equal_or_less( const Key& key ) const
  26. {
  27. if(self::size() == 0) {
  28. return self::end();
  29. } else {
  30. const_iterator equal_or_greater = self::lower_bound(key);
  31. if(equal_or_greater == self::end()) {
  32. // no element is equal or greater, so take the last
  33. return --self::end();
  34. } else if(*equal_or_greater == key) {
  35. return equal_or_greater;
  36. } else if(equal_or_greater == self::begin()) {
  37. return self::end();
  38. } else {
  39. return --equal_or_greater;
  40. }
  41. }
  42. }
  43. const_iterator equal_or_less_or_max( const Key& key ) const
  44. {
  45. const_iterator eq_or_less = self::equal_or_less(key);
  46. if(eq_or_less == self::end()) {
  47. return self::max();
  48. } else {
  49. return eq_or_less;
  50. }
  51. }
  52. const_iterator greater_or_min( const Key& key ) const
  53. {
  54. const_iterator greater = self::upper_bound(key);
  55. if(greater == self::end()) {
  56. return min();
  57. } else {
  58. return greater;
  59. }
  60. }
  61. // returns an iterator pointing to the last element that is less than key.
  62. const_iterator less( const Key& key ) const
  63. {
  64. const_iterator lower = self::lower_bound(key);
  65. if(lower == self::begin()) {
  66. return self::end();
  67. } else {
  68. lower--;
  69. return lower;
  70. }
  71. }
  72. const_iterator less_or_max( const Key& key ) const
  73. {
  74. const_iterator less = self::less(key);
  75. if(less == self::end()) {
  76. return self::max();
  77. } else {
  78. return less;
  79. }
  80. }
  81. const_iterator max() const
  82. {
  83. const_iterator max = self::end();
  84. if(self::size() > 0) {
  85. max--;
  86. }
  87. return max;
  88. }
  89. const_iterator min() const
  90. {
  91. return self::begin();
  92. }
  93. };