0

78.2 Practice - Your Queue!

You are making a queue management system and need to support different data types - for example, you should be able to queue names which are strings or integer numbers. So, you decide to make a Queue class template, which will store an array for the queue, and have add() and get() methods. You first create a class for integers only, to see if it works. My code as below, added template <class T> at 2 different places but it says it shadows the existing code.

8th Jan 2022, 12:20 AM
Chin Eu
Chin Eu - avatar
3 Réponses
+ 5
#include <iostream> using namespace std; //change the class to a template template <class T> class Queue { private: T *arr; int count; public: Queue(int size) { arr = new T[size]; count = 0; } void add(T elem) { arr[count] = elem; count++; } void get(int index) { cout << arr[index]<<endl; } }; int main() { Queue<string> q(4); q.add("James"); q.add("Andy"); q.add("Amy"); q.get(2); Queue <int> n(2); n.add(42); n.add(33); n.get(1); return 0; }
29th Jan 2023, 10:10 PM
Karla González Polanco
0
#include <iostream> using namespace std; //change the class to a template template <class T> class Queue { private: int *arr; int count; public: Queue(int size) { arr = new int[size]; count = 0; } template <class T> void add(int elem) { arr[count] = elem; count++; } void get(int index) { cout << arr[index]<<endl; } }; int main() { Queue<string> q(4); q.add("James"); q.add("Andy"); q.add("Amy"); q.get(2); Queue <int> n(2); n.add(42); n.add(33); n.get(1); return 0; }
8th Jan 2022, 12:21 AM
Chin Eu
Chin Eu - avatar
0
Found the answer: Change <int> to <T> except for <int count> and <int main> Remove “template <class T>” before “void add(int elem)”
8th Jan 2022, 6:36 AM
Chin Eu
Chin Eu - avatar