C++練習問題行列の合計--演算子の再ロード
ProblemU:C++練習問題行列の合計--再ロード演算子
Time Limit: 1 Sec
Memory Limit: 128 MB
Submit: 839
Solved: 309
[ Submit][ Status][ Web Board]
Description
2つのマトリクスaとbがあり、いずれも2行3列である.2つの行列の和を求める.マトリクス加算(c=a+bなど)に使用できるように、リロード演算子「+」を使用します.リロードストリーム挿入演算子「<<」とストリーム抽出演算子「>」は、マトリクスの入力と出力に使用できるようにします.
Input
2つの2行3列マトリクス
Output
マトリックスの和
Sample Input
Sample Output
HINT
前置コードおよびタイプ定義は、コミット時に含める必要がなく、プログラムの前部/*C++コード*/#includeusing namespace stdに自動的に追加されます.class Matrix { public: Matrix(); friend Matrix operator+(Matrix &,Matrix &); friend ostream& operator<<(ostream&,Matrix&); friend istream& operator>>(istream&,Matrix&); private: int mat[2][3]; }; 主関数は以下のように与えられており、コミット時に含める必要はなく、プログラムの末尾/*C++コード*/int main(){Matrix a,b,c;cin>>a;cin>>b;c=a+b;cout<
Time Limit: 1 Sec
Memory Limit: 128 MB
Submit: 839
Solved: 309
[ Submit][ Status][ Web Board]
Description
2つのマトリクスaとbがあり、いずれも2行3列である.2つの行列の和を求める.マトリクス加算(c=a+bなど)に使用できるように、リロード演算子「+」を使用します.リロードストリーム挿入演算子「<<」とストリーム抽出演算子「>」は、マトリクスの入力と出力に使用できるようにします.
Input
2つの2行3列マトリクス
Output
マトリックスの和
Sample Input
1 2 3
4 5 6
7 8 9
1 2 3
Sample Output
8 10 12
5 7 9
HINT
前置コードおよびタイプ定義は、コミット時に含める必要がなく、プログラムの前部/*C++コード*/#include
#include <iostream>
using namespace std;
class Matrix
{
public:
Matrix();
friend Matrix operator+(Matrix &,Matrix &);
friend ostream& operator<<(ostream&,Matrix&);
friend istream& operator>>(istream&,Matrix&);
private:
int mat[2][3];
};
Matrix::Matrix()
{
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
mat[y][x]=0;
}
}
}
Matrix operator+(Matrix &m1,Matrix &m2)
{
Matrix m;
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
m.mat[y][x]=m1.mat[y][x]+m2.mat[y][x];
}
}
return m;
}
istream& operator>>(istream&input,Matrix&m)
{
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
input>>m.mat[y][x];
}
}
return input;
}
ostream& operator<<(ostream&output,Matrix&m)
{
int x,y;
for(y=0; y<2; ++y)
{
for(x=0; x<3; ++x)
{
if(x<2)
output<<m.mat[y][x]<<' ';
else
output<<m.mat[y][x];
}
if(y<1)
{
cout<<endl;
}
}
return output;
}
int main()
{
Matrix a,b,c;
cin>>a;
cin>>b;
c=a+b;
cout<<c<<endl;
return 0;
}