HackerRank C++ Operator Overloading




Classes define new types in C++. Types in C++ not only interact by means of constructions and assignments but also via operators.



  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7. class Matrix
  8. {
  9. public:
  10. vector<vector<int> > a;
  11. Matrix & operator + (const Matrix &y)
  12. {
  13. for (int m=0; m<y.a.size(); ++m)
  14. {
  15. for (int n=0; n<y.a[0].size(); ++n)
  16. {
  17. this->a[m][n] = this->a[m][n] + y.a[m][n];
  18. }
  19. }
  20. return *this;
  21. }
  22. };
  23. int main ()
  24. {
  25. int cases,k;
  26. cin >> cases;
  27. for(k=0;k<cases;k++)
  28. {
  29. Matrix x;
  30. Matrix y;
  31. Matrix result;
  32. int n,m,i,j;
  33. cin >> n >> m;
  34. for(i=0;i<n;i++)
  35. {
  36. vector<int> b;
  37. int num;
  38. for(j=0;j<m;j++)
  39. {
  40. cin >> num;
  41. b.push_back(num);
  42. }
  43. x.a.push_back(b);
  44. }
  45. for(i=0;i<n;i++)
  46. {
  47. vector<int> b;
  48. int num;
  49. for(j=0;j<m;j++)
  50. {
  51. cin >> num;
  52. b.push_back(num);
  53. }
  54. y.a.push_back(b);
  55. }
  56. result = x+y;
  57. for(i=0;i<n;i++)
  58. {
  59. for(j=0;j<m;j++)
  60. {
  61. cout << result.a[i][j] << " ";
  62. }
  63. cout << endl;
  64. }
  65. }
  66. return 0;
  67. }




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