1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <iostream>
#include <string>
struct Job {
int id {};
std::string name;
int pages {};
};
std::ostream& operator<<(std::ostream& os, const Job& j) {
return os << j.id << ", " << j.name << ", " << j.pages;
}
template <typename T>
class Printer {
private:
T* q_array {};
size_t q_capacity {}, q_size {}, q_front {}, q_back {};
public:
Printer(size_t newCapacity);
bool isEmpty() const;
bool isFull() const;
size_t qSize() const;
void displayFront() const;
void displayBack() const;
void enqueue(T newData);
void dequeue();
void clear();
void displayAll() const;
~Printer() {
delete[] q_array;
}
// These need to be provided if needed
Printer(const Printer&) = delete;
Printer& operator=(const Printer&) = delete;
};
template <typename T>
Printer<T>::Printer(size_t newCapacity) : q_capacity { newCapacity }, q_array { new T[newCapacity] } {}
template <typename T>
bool Printer<T>::isEmpty() const {
return q_size == 0;
}
template <typename T>
bool Printer<T>::isFull() const {
return q_size == q_capacity;
}
template <typename T>
size_t Printer<T>::qSize() const {
return q_size;
}
template <typename T>
void Printer<T>::displayFront() const {
if (isEmpty())
std::cout << "Queue is empty\n";
else
std::cout << "Front: " << q_array[q_front] << '\n';
}
template <typename T>
void Printer<T>::displayBack() const {
if (isEmpty())
std::cout << "Queue is empty\n";
else
std::cout << "Back: " << q_array[q_back ? (q_back - 1) : q_capacity - 1] << '\n';
}
template <typename T>
void Printer<T>::clear() {
q_size = 0;
q_front = 0;
q_back = 0;
}
template <typename T>
void Printer<T>::enqueue(T newData) {
if (isFull())
std::cout << "Queue is Full.\n";
else {
q_array[q_back] = newData;
q_back = (q_back + 1) % q_capacity;
++q_size;
//std::cout << newData << " was successfully enqueued.\n";
}
}
template<typename T>
void Printer<T>::dequeue() {
if (isEmpty())
std::cout << "Queue is Empty.\n";
else {
const auto temp { q_array[q_front] };
q_front = (q_front + 1) % q_capacity;
--q_size;
//std::cout << temp << " was successfully dequeued.\n";
}
}
template<typename T>
void Printer<T>::displayAll() const {
std::cout << "Printing queue\n";
for (size_t i { q_front }, c {}; c < q_size; i = (i + 1) % q_capacity, ++c)
std::cout << q_array[i] << '\n';
std::cout << '\n';
}
int main() {
Printer<Job> jobQ(10);
jobQ.enqueue({1, "name1", 2});
jobQ.enqueue({ 3, "name2", 4 });
jobQ.displayAll();
}
| |