ROSE  0.9.10.44
Stack.h
1 // WARNING: Changes to this file must be contributed back to Sawyer or else they will
2 // be clobbered by the next update from Sawyer. The Sawyer repository is at
3 // https://github.com/matzke1/sawyer.
4 
5 
6 
7 
8 #ifndef Sawyer_Stack_H
9 #define Sawyer_Stack_H
10 
11 #include <Sawyer/Assert.h>
12 #include <Sawyer/Sawyer.h>
13 #include <vector>
14 
15 namespace Sawyer {
16 namespace Container {
17 
22 template<typename T>
23 class Stack {
24 public:
25  typedef T Value;
26 private:
27  std::vector<T> vector_;
28 public:
30  Stack() {}
31 
33  template<class Iterator>
34  Stack(const boost::iterator_range<Iterator> &range) {
35  for (Iterator iter=range.begin(); iter!=range.end(); ++iter)
36  vector_.push_back(*iter);
37  }
38 
39  // FIXME[Robb P. Matzke 2014-08-06]: we need iterators, values(), begin(), end(), etc.
40 
42  size_t size() const {
43  return vector_.size();
44  }
45 
49  bool isEmpty() const {
50  return vector_.empty();
51  }
52 
58  Value& top() {
59  ASSERT_forbid(isEmpty());
60  return vector_.back();
61  }
62  const Value& top() const {
63  ASSERT_forbid(isEmpty());
64  return vector_.back();
65  }
74  Value& get(size_t idx) {
75  ASSERT_require(idx < size());
76  return vector_[vector_.size() - (idx+1)];
77  }
78  const Value& get(size_t idx) const {
79  ASSERT_require(idx < size());
80  return vector_[vector_.size() - (idx+1)];
81  }
82  Value& operator[](size_t idx) { return get(idx); }
83  const Value& operator[](size_t idx) const { return get(idx); }
90  Stack& push(const Value &value) {
91  vector_.push_back(value);
92  return *this;
93  }
94 
99  Value pop() {
100  Value v = top();
101  vector_.pop_back();
102  return v;
103  }
104 };
105 
106 } // namespace
107 } // namespace
108 
109 #endif
Stack(const boost::iterator_range< Iterator > &range)
Construct a stack from an iterator range.
Definition: Stack.h:34
Name space for the entire library.
Definition: Access.h:13
Stack & push(const Value &value)
Push new item onto stack.
Definition: Stack.h:90
Stack()
Construct an empty stack.
Definition: Stack.h:30
size_t size() const
Returns the number of items on the stack.
Definition: Stack.h:42
Value & operator[](size_t idx)
Access an item not at the top of the stack.
Definition: Stack.h:82
Value pop()
Pop existing item from stack.
Definition: Stack.h:99
const Value & top() const
Returns the top item.
Definition: Stack.h:62
const Value & operator[](size_t idx) const
Access an item not at the top of the stack.
Definition: Stack.h:83
Stack-based container.
Definition: Stack.h:23
bool isEmpty() const
Determines if the stack is empty.
Definition: Stack.h:49
Value & top()
Returns the top item.
Definition: Stack.h:58