写的有点烦了,不过你看的懂就可以:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef vector<vector<int> > matrix;
typedef vector<int> row;
void GetMatrix(matrix& m)
{
row tmp;
int n;
size_t size = 0;
while(cin.peek() != '#')
{
cin.unsetf(ios::skipws);
while(cin && cin.peek() != '\n')
{
while(cin.peek() == ' ')
cin.get();
if(cin.peek() == '#')
break;
cin >> n;
while(cin.peek() == ' ')
cin.get();
tmp.push_back(n);
}
if(cin.peek() != '#')
cin.get();
if(!cin)
{
cerr << "ERROR: Invalid input characters.\n";
exit(0);
}
if(size != 0 && size != tmp.size())
{
cerr << "ERROR: Jagged matrix not allowed.\n";
exit(0);
}
size = tmp.size();
m.push_back(tmp);
tmp.clear();
}
cin.ignore(512, '\n');
}
void PrintMatrix(const matrix& m)
{
static char num[32];
int max = *max_element(m[0].begin(), m[0].end());
int n;
for(size_t i = 1; i < m.size(); ++i)
if(max < (n = *max_element(m[i].begin(), m[i].end())))
max = n;
sprintf(num, "%d", max);
cout.setf(ios::left);
for(size_t i = 0; i < m.size(); ++i)
{
for(size_t j = 0; j < m[i].size(); ++j)
{
cout.width(strlen(num));
cout << m[i][j] << ' ';
}
cout << '\n';
}
}
void MatrixMul(const matrix& m1, const matrix& m2, matrix& product)
{
if(m1[0].size() != m2.size())
{
cerr << "Candidate not allowed.\n";
cerr << "If m1 is a m * n matrix so m2 must be a n * p matrix.\n";
exit(0);
}
for(size_t i = 0; i < m1.size(); ++i)
{
product.push_back(row());
for(size_t j = 0; j < m2[0].size(); ++j)
{
product[i].push_back(0);
for(size_t k = 0; k < m1[0].size(); ++k)
product[i][j] += m1[i][k] * m2[k][j];
}
}
}
int main()
{
matrix m1, m2, m3;
cout << "Enter matrix1:\n";
GetMatrix(m1);
cout << "\nEnter matrix2:\n";
GetMatrix(m2);
MatrixMul(m1, m2, m3);
cout << "\n\nmatrix 1: " << m1.size() << " × "<< m1[0].size() << '\n';
PrintMatrix(m1);
cout << "\n\nmatrix 2: " << m2.size() << " × "<< m2[0].size() << '\n';
PrintMatrix(m2);
cout << "\n\nm1 * m2: " << m3.size() << " × "<< m3[0].size() << '\n';
PrintMatrix(m3);
}
温馨提示:答案为网友推荐,仅供参考