discoverpixy
simplevector.h
1 //
2 // begin license header
3 //
4 // This file is part of Pixy CMUcam5 or "Pixy" for short
5 //
6 // All Pixy source code is provided under the terms of the
7 // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html).
8 // Those wishing to use Pixy source code, software and/or
9 // technologies under different licensing terms should contact us at
10 // cmucam@cs.cmu.edu. Such licensing terms are available for
11 // all portions of the Pixy codebase presented here.
12 //
13 // end license header
14 //
15 
16 #ifndef SIMPLEVECTOR_H
17 #define SIMPLEVECTOR_H
18 
19 #include <new>
20 
21 #define SPARE_CAPACITY 16
22 
23 template <typename Object> class SimpleVector
24 {
25 public:
26 
27  SimpleVector(int initSize = 0)
28  : m_size(0), m_capacity(initSize + SPARE_CAPACITY)
29  { m_objects = new Object[m_capacity]; }
30 
31  ~SimpleVector()
32  { delete [] m_objects; }
33 
34  int resize(int newCapacity)
35  {
36  if(newCapacity < m_size)
37  return 0;
38 
39  Object *oldArray = m_objects;
40 
41  m_objects = new (std::nothrow) Object[newCapacity];
42  if (m_objects==NULL)
43  {
44  m_objects = oldArray;
45  return -1;
46  }
47  for(int k = 0; k<m_size; k++)
48  m_objects[k] = oldArray[k];
49 
50  m_capacity = newCapacity;
51 
52  delete [] oldArray;
53  return 0;
54  }
55 
56  Object & operator[](int index)
57  { return m_objects[index]; }
58 
59  const Object& operator[](int index) const
60  { return m_objects[index]; }
61 
62  bool empty() const
63  { return size()==0; }
64 
65  int size() const
66  { return m_size; }
67 
68  int capacity() const
69  { return m_capacity; }
70 
71  const Object *data()
72  { return m_objects; }
73 
74  int push_back(const Object& x)
75  {
76  if(m_size == m_capacity)
77  if (resize(m_capacity + SPARE_CAPACITY)<0)
78  return -1;
79  m_objects[m_size++] = x;
80  return 0;
81  }
82 
83  void pop_back()
84  { m_size--; }
85 
86  void clear()
87  { m_size = 0; }
88 
89 private:
90  int m_size;
91  int m_capacity;
92  Object *m_objects;
93 };
94 
95 #endif // SIMPLEVECTOR_H
Definition: simplevector.h:23