Skip to content

Commit 06ef498

Browse files
committed
Comparator structure added
1 parent 5e4dbf0 commit 06ef498

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

Miscellaneous/01 Operator Overloading for Sorting (Part 1).cpp

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ class Node
7272
}
7373
};
7474

75-
ostream &operator <<(ostream &os, Node &node)
75+
ostream &operator <<(ostream &os, const Node &node)
7676
{
7777
os<<"Id : "<<node.id<<" , Cost : "<<node.cost<<" , Name : "<<node.name;
7878
return os;
@@ -86,10 +86,26 @@ bool cmp(const Node &A,const Node &B) /** Sort with descending order of cost **/
8686
return A.cost>B.cost;
8787
}
8888

89+
struct Comparator
90+
{
91+
bool operator()(const Node &A,const Node &B) /** Sort with descending order of cost **/
92+
{
93+
if(A.cost==B.cost)
94+
return A.name<B.name;
95+
96+
return A.cost>B.cost;
97+
}
98+
};
99+
100+
89101
int main()
90102
{
91103
optimizeIO();
92104

105+
/**
106+
VECTOR
107+
**/
108+
93109
vector<Node>v;
94110

95111
v.push_back(Node(1,100,"C"));
@@ -100,10 +116,42 @@ int main()
100116

101117
cout<<v<<endl;
102118

103-
sort(ALL(v),cmp);
119+
sort(ALL(v),cmp); /** comparator function **/
120+
sort(ALL(v),Comparator()); /** comparator structure **/
104121

105122
cout<<v<<endl;
106123

124+
/**
125+
SET
126+
**/
127+
128+
set<Node,Comparator>st; /** Uses the Comparator structure **/
129+
st.insert(Node(1,100,"C"));
130+
st.insert(Node(1,100,"A"));
131+
st.insert(Node(1,100,"B"));
132+
st.insert(Node(1,500,"AB"));
133+
st.insert(Node(1,50,"ABC"));
134+
135+
for(auto x:st)
136+
cout<<x.cost<<" "<<x.name<<endl;
137+
138+
/**
139+
Priority Queue
140+
PRIORITY QUEUE is MAX HEAP by default .
141+
So , the result will be opposite of what we got in SET .
142+
**/
143+
144+
priority_queue<Node,vector<Node>,Comparator>pq;
145+
pq.push(Node(1,100,"C"));
146+
pq.push(Node(1,100,"A"));
147+
pq.push(Node(1,100,"B"));
148+
pq.push(Node(1,500,"AB"));
149+
pq.push(Node(1,50,"ABC"));
150+
151+
while(!pq.empty())
152+
cout<<pq.top()<<" ", pq.pop();
153+
cout<<endl;
154+
107155
return 0;
108156
}
109157

Miscellaneous/01 Operator Overloading for Sorting (Part 2).cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,10 @@ int main()
9090
{
9191
optimizeIO();
9292

93+
/**
94+
VECTOR
95+
**/
96+
9397
vector<Node>v;
9498

9599
v.push_back(Node(1,100,"C"));
@@ -104,6 +108,10 @@ int main()
104108

105109
cout<<v<<endl;
106110

111+
/**
112+
SET
113+
**/
114+
107115
set<Node>st; /** Uses the overloaded < operator **/
108116
st.insert(Node(1,100,"C"));
109117
st.insert(Node(1,100,"A"));

0 commit comments

Comments
 (0)