1
+
1
2
#include < iostream>
2
3
#include < queue> // priority_queue
3
4
#include < vector>
5
+ #include < unordered_map>
4
6
5
7
using namespace std ;
6
8
@@ -12,8 +14,10 @@ class mycomparison{
12
14
}
13
15
};
14
16
15
- int main ()
16
- {
17
+ // https://stackoverflow.com/questions/5807735/c-priority-queue-with-lambda-comparator-error
18
+
19
+ int main (){
20
+ /* **Example 1***/
17
21
priority_queue<int , vector<int >, mycomparison> pq;
18
22
vector<int > v = {1 ,7 ,2 ,9 ,3 ,0 ,4 ,5 ,-3 ,-9 ,-4 ,-2 };
19
23
@@ -25,6 +29,45 @@ int main()
25
29
cout << pq.top () << " " ;
26
30
pq.pop ();
27
31
}
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
+
29
67
return 0 ;
30
68
}
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