-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsparse matrix overloading.cpp
More file actions
109 lines (97 loc) · 2.12 KB
/
Copy pathsparse matrix overloading.cpp
File metadata and controls
109 lines (97 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//this program contain the Sparse matrix and in this program we will see how to overload sparse matrix
#include<iostream>
using namespace std;
//declaring the class
class Element {
public :
int i,j,x;
} ;
class Sparse{
private :
int m,n,num;
Element *ele;
public ://public element
Sparse(int m,int n,int num)
{
this->m = m;
this->n = n;
this->num = num;
ele= new Element[this->num];
}
//de-constructor
~Sparse(){
delete[] ele;
}
Sparse operator +(Sparse &s);
friend istream & operator>>(istream &is,Sparse &s);
friend ostream & operator<<(ostream &os,Sparse &s);
};
//sparse matrix function
Sparse Sparse::operator +(Sparse &s)
{
int i,j,k;
Sparse *sum=new Sparse(m,n,num+s.num);
i=j=k=0;
while(i<s.num && j<s.num)
{
if(ele[i].i<s.ele[j].i)
sum->ele[k++]=ele[i++];
else if(ele[i].i>s.ele[j].i)
sum->ele[k++]=s.ele[j++];
else
{
if(ele[i].j<s.ele[j].j)
sum->ele[k++]=ele[i++];
else
if(ele[i].j>s.ele[j].j)
sum->ele[k++]=s.ele[j++];
else
{
sum->ele[k]=ele[i];
sum->ele[k++].x=s.ele[i++].x+s.ele[j++].x;
}
}
}
for(;i<num;i++) sum->ele[k++]=ele[i];
for(;j<num;j++) sum->ele[k++]=s.ele[j];
sum->num=k;
return *sum;
}
//input function
istream & operator>>(istream &is,Sparse &s)
{
cout<<"Enter non-zero number of elements";
for(int i=0;i<s.num;i++)
cin>>s.ele[i].i>>s.ele[i].j>>s.ele[i].x;
return is;
}
//out function
ostream & operator<<(ostream &os,Sparse &s)
{
int k=0;
for(int i=0;i<s.m;i++)
{
for(int j=0;j<s.n;j++)
{
if(s.ele[k++].i==i && s.ele[k].j==j)
cout<<s.ele[k++].x<<" ";
else
cout<<"0 ";
}
cout<<endl;
}
return os;
}
//main
int main()
{
Sparse s1(5,5,5);
Sparse s2(5,5,5);
cin>>s1;
cin>>s2;
Sparse sum=s1+s2;
cout<<"First matrix "<<endl<<s1;
cout<<"Second matrix "<<endl<<s2;
cout<<"Sum of matrixs "<<endl<<sum;
return 0;
}