Skip to content

Commit 01e01ce

Browse files
add Example 2: capture varialbe in lambda function
1 parent 8c5b7ca commit 01e01ce

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

priority_queue_custom_comparison.cpp

+46-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
12
#include <iostream>
23
#include <queue> //priority_queue
34
#include <vector>
5+
#include <unordered_map>
46

57
using namespace std;
68

@@ -12,8 +14,10 @@ class mycomparison{
1214
}
1315
};
1416

15-
int main()
16-
{
17+
//https://stackoverflow.com/questions/5807735/c-priority-queue-with-lambda-comparator-error
18+
19+
int main(){
20+
/***Example 1***/
1721
priority_queue<int, vector<int>, mycomparison> pq;
1822
vector<int> v = {1,7,2,9,3,0,4,5,-3,-9,-4,-2};
1923

@@ -25,6 +29,45 @@ int main()
2529
cout << pq.top() << " ";
2630
pq.pop();
2731
}
28-
//0 1 2 -2 3 -3 4 -4 5 7 -9 9
32+
cout << endl;
33+
34+
/***Example 2: capture varialbe in lambda function***/
35+
unordered_map<string, int> counter =
36+
{
37+
{"a", 1},
38+
{"aa",1},
39+
{"aaa",1},
40+
{"b",3},
41+
{"c",2}
42+
};
43+
44+
//sort by their count, and then by lexicographical order
45+
auto comp = [&counter](const string& lhs, const string& rhs){
46+
/*if we want an element to be popped from priority queue earlier,
47+
then we need to make it rank lower in the sorted array
48+
*/
49+
// cout << lhs << " " << counter[lhs] << " " << rhs << " " << counter[rhs] << endl;
50+
// cout << lhs << " " << rhs << " " << (lhs > rhs) << endl;
51+
return (counter[lhs] == counter[rhs]) ? (lhs > rhs) :
52+
(counter[lhs] < counter[rhs]);
53+
};
54+
55+
priority_queue<string , vector<string>, decltype(comp)> pq2(comp);
56+
57+
for(auto it = counter.begin(); it != counter.end(); it++){
58+
pq2.push(it->first);
59+
}
60+
61+
while(!pq2.empty()){
62+
cout << pq2.top() << " ";
63+
pq2.pop();
64+
}
65+
cout << endl;
66+
2967
return 0;
3068
}
69+
70+
/*
71+
0 1 2 -2 3 -3 4 -4 5 7 -9 9
72+
b c a aa aaa
73+
*/

0 commit comments

Comments
 (0)