稀疏矩阵的存取

// test21.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include
<iostream>
#include
<vector>
#include
<iomanip>
using namespace std;

template
<class T>
class Matrix;

template 
<class T>
class Term{//矩阵中每个三元组的元素
public:
    Term(
int r,int c,T v):row(r),col(c),val(v){}
//private:
    int row, col;//元素的行标,列标
    T val;//元素的值
    friend class Matrix<T>;
};

template 
<class T>
class Matrix{//矩阵
    template<class T>
    friend istream
& operator>>(istream&, Matrix<T>&);
    template
<class T>
    friend ostream
& operator<<(ostream&, Matrix<T>&);
public:
    Matrix(){mRow
=0, mCol=0, nZeroNum=0;}
private:
    vector
<Term<T>> vec;
    
int mRow,mCol;//矩阵的行数,列数
    int nZeroNum;//矩阵中的非零元素个数
};

template
<class T>
istream
& operator>>(istream& in, Matrix<T>& m){//输入矩阵
    cout<<"Enter the Row and Col of the Matrix: ";
    
in>>m.mRow>>m.mCol;    //输入矩阵的行数和列数
    cout<<"Enter the none Zeor Number of the Matrix: ";
    
in>>m.nZeroNum;//输入矩阵的非零元个数
    int r,c;
    T v;
    
int k=m.nZeroNum;
    
while(k--!=0){
        cout
<<"Enter the Elements of the Matrix: ";
        
in>>r>>c>>v;//矩阵中每一个非零元的行标,列标和值
        m.vec.push_back(Term<T>(r,c,v));//将元素存到容器中去
    }
    
return in;
}

template
<class T>
ostream
& operator<<(ostream& out, Matrix<T>& m){//输出矩阵
    
//不用STL迭代器,手写如下
    
//int k=0;//用于遍历vec中的每一个值
    
//for(int i=0;i<m.mRow;i++){
    
//    for(int j=0;j<m.mCol;j++){
    
//        if(m.vec[k].row==i && m.vec[k].col==j)//如果m中vec中的第k个非零元素对应行标=i,列标=j,则输出该值
    
//            out<<setw(4)<<m.vec[k++].val;
    
//        else
    
//            out<<setw(4)<<"0";    //如果不存在第k个元素,输出0
    
//    }
    
//    out<<endl;
    
//}
    vector<Term<T>>::iterator iter=m.vec.begin(); 
    
while(iter!=m.vec.end()){
        
for(int i=0;i<m.mRow;i++){
            
for(int j=0;j<m.mCol;j++){
                
if(iter->row==&& iter->col==j){
                    
out<<setw(4)<<iter->val;//如果存在非零元素,则打印
                    iter++;
                }
                
else
                    
out<<setw(4)<<"0";//否则打印0                
            }
            
out<<endl;
        }
    }
    
return out;
}

int main(){
    Matrix
<int> m;
    cin
>>m;
    cout
<<m;
    system(
"pause");
}



运行结果如下:
Enter the Row and Col of the Matrix: 3 3
Enter the none Zeor Number of the Matrix: 3
Enter the Elements of the Matrix: 0 0 1
Enter the Elements of the Matrix: 1 1 2
Enter the Elements of the Matrix: 2 2 3
   1   0   0
   0   2   0
   0   0   3

posted on 2008-10-26 16:41 deep2 阅读(1528) 评论(0)  编辑 收藏 引用 所属分类: 矩阵


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜