fast_back_stack 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
  2. *
  3. * This library is open source and may be redistributed and/or modified under
  4. * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
  5. * (at your option) any later version. The full license is in LICENSE file
  6. * included with this distribution, and on the openscenegraph.org website.
  7. *
  8. * This library is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * OpenSceneGraph Public License for more details.
  12. */
  13. #ifndef OSG_FAST_BACK_STACK
  14. #define OSG_FAST_BACK_STACK 1
  15. #include <vector>
  16. namespace osg {
  17. /** Simple stack implementation that keeps the back() cached locally for fast access
  18. * rather than at the back of the vector which is the traditional stack implementation.
  19. * A conventional std::vector<> stores the rest of the stack. Although fast_back_stack
  20. * contains a stl container it only implements the back push_back(),pop_back()
  21. * and back() methods so is not as general purpose as stl stack implementation.
  22. * The focus of the fast_back_stack is purely to maximize the speed at which the
  23. * back can be accessed.*/
  24. template<class T>
  25. class fast_back_stack
  26. {
  27. public:
  28. inline fast_back_stack():_value(),_stack(),_size(0) {}
  29. inline fast_back_stack(const fast_back_stack& fbs):_value(fbs._value),_stack(fbs._stack),_size(fbs._size) {}
  30. inline fast_back_stack(const T& value):_value(value),_stack(),_size(1) {}
  31. fast_back_stack& operator = (const fast_back_stack& fbs)
  32. {
  33. _value = fbs._value;
  34. _stack = fbs._stack;
  35. _size = fbs._size;
  36. return *this;
  37. }
  38. inline void clear() { _stack.clear(); _size = 0; }
  39. inline bool empty() const { return _size==0; }
  40. inline unsigned int size() const { return _size; }
  41. inline T& back() { return _value; }
  42. inline const T& back() const { return _value; }
  43. inline void push_back()
  44. {
  45. if (_size>0)
  46. {
  47. _stack.push_back(_value);
  48. }
  49. ++_size;
  50. }
  51. inline void push_back(const T& value)
  52. {
  53. if (_size>0)
  54. {
  55. _stack.push_back(_value);
  56. }
  57. _value = value;
  58. ++_size;
  59. }
  60. inline void pop_back()
  61. {
  62. if (_size>0)
  63. {
  64. if (!_stack.empty())
  65. {
  66. _value = _stack.back();
  67. _stack.pop_back();
  68. }
  69. --_size;
  70. } // else error condition.
  71. }
  72. T _value;
  73. std::vector<T> _stack;
  74. unsigned int _size;
  75. };
  76. }
  77. #endif