02-queue
02-queue
DATA STRUCTURES
2
Specication
4
const member functions
5
Design by contract
6
Dynamic-array representation
1 private:
2 T *data;
3 size_type front, used, capacity;
4
5 /* Invariants:
6 1) the queue elements are stored in data[front], data[(front+1)% capacity], ...,
7 2) data[(front+used-1) % capacity] in increasing order of insertion time
8
9 3) used = number of elements in this queue
10
11 4) capacity = physical size of data
12 */
7
Implementation
26 assert(!empty());
1 queue(size_type init_capacity = INIT_CAPACITY) 27 return data[front];
2 { 28 }
3 front = used = 0; 29
4 capacity = init_capacity; 30 void pop()
5 data = new T[capacity]; 31 {
6 } 32 assert(!empty());
7 33 front = (front + 1) % capacity;
8 bool empty() const 34 --used;
9 { 35 }
10 return (used == 0); 36
11 } 37 void push(const T & entry)
12 38 {
13 size_type size() const 39 if (used == capacity)
14 { 40 {
15 return used; 41 capacity *= 2;
16 } 42 T *newdata = new T[capacity];
17 43 std::copy(data+front, data+used, newdata);
18 T & front() const 44 std::copy(data, data+front,
19 { 45 newdata+used - front);
20 assert(!empty()); 46 front = 0;
21 return data[front]; 47 delete [] data;
22 } 48 data = newdata;
23 49 }
24 T & front() 50 data[(front+used++) % capacity] = entry;
25 { 51 }
8
Linked-list representation
1 private:
2 std::list<T> _l;
3
4 /* invariants:
5 1) the items in this queue are stored in a doubly linked list _l in order of insertion
6 2) the oldest element is at the front of _l and the newest element is at the back of _l
7 */
9
Implementation
19 return _l.front();
1 queue() 20 }
2 { 21
3 _l = std::list<T>(); 22 T & front()
4 } 23 {
5 24 assert(!empty());
6 bool empty() const 25 return _l.front();
7 { 26 }
8 return (_l.size() == 0); 27
9 } 28 void push(const T & entry)
10 29 {
11 size_type size() const 30 _l.push_back(entry);
12 { 31 }
13 return _l.size(); 32
14 } 33 void pop()
15 34 {
16 T & front() const 35 assert(!empty());
17 { 36 _l.pop_front();
18 assert(!empty()); 37 }
10
Application: Queuing Theory
Single-server queues
11
Technical details: Poisson process
12
Simulation
13
Find a formula based on arrival and service rates
1 int main()
2 {
3 srand(time(0));
4 const std::size_t N(1000000);
5
6 cout << average_visit_time(1.0, 5.0, N) << endl;
7 cout << average_visit_time(1.0, 3.0, N) << endl;
8 cout << average_visit_time(1.0, 2.0, N) << endl;
9 cout << average_visit_time(1.0, 1.5, N) << endl;
10 cout << average_visit_time(1.0, 1.1, N) << endl;
11 cout << average_visit_time(1.0, 1.05, N) << endl;
12 cout << average_visit_time(1.0, 1.025, N) << endl;
13 }
14