HackerRank C++ Class Templates




You are given a main() function which takes a set of inputs. The type of input governs the kind of operation to be performed, i.e. concatenation for strings and addition for int or float. You need to write the class template AddElements which has a function add() for giving the sum of int or float elements. You also need to write a template specialization for the type string with a function concatenate() to concatenate the second string to the first string.



  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <cassert>
  7. using namespace std;
  8. /*Write the class AddElements here*/
  9. template <class T> class AddElements {
  10. public:
  11. T element;
  12. AddElements(T i) {element = i;}
  13. T add(T i) {return element+i;}
  14. private:
  15. };
  16. template <> class AddElements <string> {
  17. public:
  18. string element;
  19. AddElements(string i) {element = i;}
  20. string concatenate(string element2) {return element+element2;}
  21. private:
  22. };
  23. int main () {
  24. int n,i;
  25. cin >> n;
  26. for(i=0;i<n;i++) {
  27. string type;
  28. cin >> type;
  29. if(type=="float") {
  30. double element1,element2;
  31. cin >> element1 >> element2;
  32. AddElements<double> myfloat (element1);
  33. cout << myfloat.add(element2) << endl;
  34. }
  35. else if(type == "int") {
  36. int element1, element2;
  37. cin >> element1 >> element2;
  38. AddElements<int> myint (element1);
  39. cout << myint.add(element2) << endl;
  40. }
  41. else if(type == "string") {
  42. string element1, element2;
  43. cin >> element1 >> element2;
  44. AddElements<string> mystring (element1);
  45. cout << mystring.concatenate(element2) << endl;
  46. }
  47. }
  48. return 0;
  49. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube