The spica renderer
random_queue.h
1 #ifndef _SPICA_RANDOM_QUEUE_H_
2 #define _SPICA_RANDOM_QUEUE_H_
3 
4 #include <memory>
5 #include <algorithm>
6 
7 #include "core/random.h"
8 
9 namespace spica {
10 
13  template <class T>
14  class RandomQueue {
15  private:
16  static const size_t initSize;
17 
18  size_t _size;
19  size_t _pos;
20  Random _rng;
21  std::unique_ptr<T[]> _data;
22 
23  public:
26  explicit RandomQueue(unsigned int seed = 0)
27  : _size{initSize}
28  , _pos{0}
29  , _rng{seed}
30  , _data{nullptr} {
31  _data = std::make_unique<T[]>(initSize);
32  }
33 
37  }
38 
42  : _size{0}
43  , _pos{0}
44  , _rng{}
45  , _data{nullptr} {
46  this->operator=(que);
47  }
48 
52  if (this == &que) return *this;
53 
54  _data.reset();
55 
56  _size = que._size;
57  _pos = que._pos;
58  _data = std::make_unique<T[]>(que._size);
59  std::copy(que._data.get(), que._data.get() + que._size, _data.get());
60 
61  return *this;
62  }
63 
66  void push(const T& ty) {
67  _data[_pos++] = ty;
68  if (_pos == _size) {
69  auto temp = std::make_unique<T[]>(_size * 2);
70  std::copy(_data.get(), _data.get() + _size, temp.get());
71 
72  _size *= 2;
73  _data.reset();
74  _data = std::move(temp);
75  }
76  }
77 
80  T pop() {
81  Assertion(_pos >= 0, "Queue is empty !!");
82  const int r = _rng.nextInt(_pos);
83  _pos--;
84 
85  std::swap(_data[r], _data[_pos]);
86  return _data[_pos];
87  }
88 
91  bool empty() const {
92  return _pos == 0;
93  }
94 
97  size_t size() const {
98  return _pos;
99  }
100  };
101 
102  template <class Ty>
103  const size_t RandomQueue<Ty>::initSize = 1024;
104 
105 } // namespace spica
106 
107 #endif // _SPICA_RANDOM_QUEUE_H_
RandomQueue(unsigned int seed=0)
The RandomQueue constructor.
Definition: random_queue.h:26
~RandomQueue()
The RandomQueue destructor.
Definition: random_queue.h:36
Random number generator with Mersenne twister.
Definition: random.h:17
bool empty() const
Check if the queue is empty.
Definition: random_queue.h:91
size_t size() const
Return the size of the queue.
Definition: random_queue.h:97
T pop()
Pop the random item in the queue.
Definition: random_queue.h:80
void push(const T &ty)
Push a new value.
Definition: random_queue.h:66
Queue of random-order popping.
Definition: random_queue.h:14
RandomQueue & operator=(const RandomQueue &que)
Assignment operator.
Definition: random_queue.h:51
RandomQueue(const RandomQueue &que)
The RandomQueue constructor (copy).
Definition: random_queue.h:41