We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<iostream>#include<vector>#include<cstddef>classMatrix{public:Matrix()=default;Matrix(std::size_trows,std::size_tcolumns):m_rows{rows},m_columns{columns},m_matrix{std::vector<std::vector<int>>(m_rows,std::vector<int>(m_columns))}{}friendMatrixoperator+(constMatrix&m1,constMatrix&m2){// The matrix has to have depthMatrixm3{m1.m_rows,m1.m_columns};for(std::size_tr{0};r<m1.m_rows;++r){for(std::size_tc{0};c<m1.m_columns;++c){m3(r,c)=m1(r,c)+m2(r,c);}}returnm3;}friendstd::ostream&operator<<(std::ostream&out,constMatrix&m){for(constauto&r:m.m_matrix){for(constauto&c:r){out<<c<<' ';}out<<'\n';}returnout;}friendstd::istream&operator>>(std::istream&in,Matrix&m){// Loops through the matrix and populates itfor(auto&r:m.m_matrix){for(auto&c:r){in>>c;}}returnin;}// Returns a reference to an elementint&operator()(conststd::size_tr,conststd::size_tc){returnm_matrix[r][c];}// 'const' version of 'operator()'constint&operator()(conststd::size_tr,conststd::size_tc)const{returnm_matrix[r][c];}private:std::size_tm_rows{};std::size_tm_columns{};std::vector<std::vector<int>>m_matrix{};};intmain(){intnumCases{};std::cin>>numCases;while(numCases--){std::size_trows{};std::size_tcolumns{};std::cin>>rows>>columns;// Constructs blank matrices, could also use std::vector::clear()Matrixm1{};Matrixm2{};m1={rows,columns};m2={rows,columns};std::cin>>m1>>m2;std::cout<<m1+m2;}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Operator Overloading
You are viewing a single comment's thread. Return to all comments →
This was a weird one: