+ 1

your queue problem <template>

// i tried to fix it but i do not know what wrong with it. any one can help please? #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; } void add(int elem) { arr[count] = elem; count++; } void get(int index) { cout << arr[index]<<endl; } }; template<class T> T Queue<T>::add( ){ } T Queue<T>::get(){ } 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; }

11th Mar 2021, 5:54 AM
JRAMAHES
JRAMAHES - avatar
6 ответов
+ 3
Here is my solution: The variable type of arr (array) and elem (item in array) needs to be generic so both string and integer type parameters can be passed through. Other variables like count, size and index needs to remain as integer types. #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; }
31st May 2021, 8:04 PM
Yingjie Zhao
Yingjie Zhao - avatar
0
You have two methods of void type, but when you are defining them, you assigned type T as the return type. Change it to void and give these methods the body if needed If it is not problem, then share your code in code playground so it will be easy for us to check the errors etc
11th Mar 2021, 8:50 AM
Michal Doruch
0
i will thanks
11th Mar 2021, 6:40 PM
JRAMAHES
JRAMAHES - avatar
0
Michal Doruch I have a similar issue with this practice code. I changed what I think is the return type to void but get the error “No declaration matches void Queue <T>::add(){}”. I’ll post my code in the next comments. Any guidance is appreciated. Thanks!
30th May 2021, 5:15 AM
Jon Scoggins
Jon Scoggins - avatar
0
#include <iostream> using namespace std; template<class T> class Queue{ private: int *arr; int count; public: Queue(int size) { arr = new int[size]; count = 0; } void add(int elem) { arr[count] = elem; count++; } void get(int index) { cout << arr[index]<<endl; } }; template <class T> void Queue <T>::add(){} void Queue <T>::get(){} 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; }
30th May 2021, 5:15 AM
Jon Scoggins
Jon Scoggins - avatar
0
Thanks!
31st May 2021, 9:02 PM
Jon Scoggins
Jon Scoggins - avatar