方阵的生成 读写文件 转置和显示
#include <iostream>
#include <math.h>
#include <time.h>
#include <fstream>
#include <iomanip>
using namespace std;
template<class T>
int inline size(T type,char *file) {
ifstream in(file);
in.seekg(0,ios::end);
int size=in.tellg()/sizeof(type);
in.close();
return size;
}
template<class T>
void showMatrix(T** matrix,int size)
{
for(int i=0;i<size;++i)
{
for(int j=0;j<size;++j)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
template<class T>
int readMatrix(char* file,T **matrix,int size)
{
ifstream in(file,ios::binary);
if(in==NULL)
{
cout<<"error"<<endl;
return 0;
}
cout<<"start reading"<<endl;
for(int i=0;i<size;++i)
{
in.seekg(i*size*sizeof(T),ios::beg);//each time read a line
in.read((char*)matrix[i],size*sizeof(T));
}
in.close();
cout<<endl;
return 1;
}
template<class T>
bool generateMatrix(char* file,T **matrix,int size)
{
srand(unsigned(time(0)));
cout<<"start generating"<<endl;
for(int i=0;i<size;++i)
{
for(int j=0;j<size;++j)
{
matrix[i][j]=(T)rand();
}
}
return writeMatrix(file,matrix,size);
}
template<class T>
int writeMatrix(char* file,T** matrix,int size)
{
ofstream out(file,ios::binary);//write binary
if(out==NULL)
{
cout<<"error"<<endl;
return false;
}
cout<<"write"<<endl;
for(int i=0;i<size;++i)
{
out.write((char*)matrix[i],size*sizeof(T));//append to file
}
out.flush();
out.close();
cout<<endl;
return 1;
}
template<class T>
bool compareMatrix(T** a,T** b,int size)
{
bool same=true;
for(int i=0;i<size&&same;++i)
{
for(int j=0;j<size&&same;++j)
{
same&=(a[i][j]==b[i][j]);
if(!same)
{
cout<<i<<" "<<j<<" "<<a[i][j]<<" "<<b[i][j]<<endl;
}
}
}
return same;
}
//get the transpositioned matrix
template<class T>
void matrixTransposition(T** matrix,int size)
{
T temp;
for(int i=1;i<size;++i)
{
for(int j=0;j<i;++j)
{
temp=matrix[i][j];
matrix[i][j]=matrix[j][i];
matrix[j][i]=temp;
}
}
}