题目
matrixA.txt , shape(1,50)
matrixB.txt , shape(50,10)
1. 讀取matrixA.txt,matrixB.txt中的矩陣
2. 進行矩陣乘法 - matrixA * matrixB
3. 將得到的矩陣數值,由小到大排序後輸出至ans_one.txt,每个数字要换行
文件样式
- matrixA.txt
-matrixB.txt
直接上代码
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
//忽视硬编码
//1*50
ifstream matrixFile1("/home/wuxiao/MyGithub/ML/homework1/2017ML_HW0_data/matrixA.txt");
//50*10
ifstream matrixFile2("/home/wuxiao/MyGithub/ML/homework1/2017ML_HW0_data/matrixB.txt");
ofstream outputFile("/home/wuxiao/MyGithub/ML/homework1/2017ML_HW0_data/Q1_ans.txt");
vector<int> matrixANum;
vector<int> matrixBNum;
vector<int> outputFileNum;
void splitString(const string& s, vector<int>& v, const string& c)
{
string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while(string::npos != pos2)
{
v.push_back(strtoll(s.substr(pos1, pos2-pos1).c_str(),NULL,10));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length())
{
v.push_back(strtoll(s.substr(pos1).c_str(),NULL,10));
}
}
void getFileNumToArray(ifstream &file,int row,vector<int> &output)
{
string tempString = "";
for(int i=0;i<row;i++)
{
getline(file,tempString);
splitString(tempString,output,",");
}
}
void getOutputNum(vector<int> &file1,vector<int> &file2,int times,vector<int> &outputFile)
{
for(int i=0;i<times;i++)
{
int sum = 0;
for(size_t j=0;j<file1.size();j++)
{
sum += file1[j] * file2[file1.size() * i + j];
}
outputFile.push_back(sum);
}
sort(outputFile.begin(),outputFile.end());
}
int main() {
if(!matrixFile1 || !matrixFile2 || !outputFile)
{
cout<<"unable to open inputFile or outputFile!"<<endl;
return -1;
}
//读取输入文件的value到数组
getFileNumToArray(matrixFile1,1,matrixANum);
getFileNumToArray(matrixFile2,50,matrixBNum);
//计算矩阵乘积结果
getOutputNum(matrixANum,matrixBNum,10,outputFileNum);
//输出写入文件
vector<int>::iterator iter = outputFileNum.begin();
for(iter = outputFileNum.begin();iter != outputFileNum.end();iter++)
{
outputFile<<*iter<<'\n';
}
return 0;
}