Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
coding_cheat_sheet [2020/10/08 00:33]
paul [Using Custom Data With Priority Queues]
coding_cheat_sheet [2021/11/08 00:09] (current)
paul [Using Custom Data With Priority Queues]
Line 136: Line 136:
  
 <code cpp> <code cpp>
-bool sortFunc(const vector<int> &v1, const vector<int> &v2)+bool compareFunc(const vector<int> &v1, const vector<int> &v2)
 { {
   return v1[0] < v2[0];   return v1[0] < v2[0];
 } }
 +
 +// use the sort function by passing in the custom compare fucnction
 +sort(myVect.begin(), myVect.end(), compareFunc);
 </code> </code>
  
Line 237: Line 240:
 cout << "Top of min_heap: " << min_heap.top() << endl; cout << "Top of min_heap: " << min_heap.top() << endl;
 // prints 1 // prints 1
 +</code>
 +==== Max Heap with Pairs ====
 +
 +By default, max heaps using type pair are ordered by the first element. You do not need to create a custom Compare class. See [[https://www.geeksforgeeks.org/priority-queue-of-pairs-in-c-ordered-by-first/|here]]
 +
 +<code cpp>
 +typedef pair<int,int> num_t;
 +
 +priority_queue<num_t> maxHeap;
 +
 +maxHeap.push(make_pair(1,2));
 +maxHeap.push(make_pair(2,2));
 +
 +// This will be true
 +assert_true(maxHeap.top().first == 2);
 </code> </code>
  
 ==== Using Custom Data With Priority Queues ==== ==== Using Custom Data With Priority Queues ====
  
-There are numerous was of doing this but here is the least verbose way.+There are numerous was of doing this but here is the most elegant way
 + 
 +<code cpp> 
 +struct node{ 
 +  node(int id, int value) : id(id), value(value){} 
 +  int id; 
 +  int value; 
 +}; 
 + 
 +auto cmp = [](const node &a, const node &b){ 
 +  //Max Heap: 
 +  //====================== 
 +  //larger b will appear later in the container and therefore have a higher priority 
 +  return a.value < b.value; 
 +   
 +  //MIN Heap: 
 +  //if a is larger than b, it will appear before b, so smaller b will have higher priority 
 +  return a.value > b.value; 
 +}; 
 + 
 +priority_queue<node, vector<node>, decltype(cmp)> maxHeap(cmp); 
 +</code> 
 + 
 +A less elegant way of overloading the default less than operator is as follows:
  
 <code cpp> <code cpp>
Line 248: Line 289:
   int id;   int id;
   int value;   int value;
-}+};
  
 bool operator<(const node& A, const node& B) { bool operator<(const node& A, const node& B) {
Line 291: Line 332:
 }; };
  
 +// This is a max heap based on number of the int in the pair, and if numbers are the same, word thats lower on the alphabetical compare wins.
 priority_queue<p_d, vector<p_d>, Compare> heap; priority_queue<p_d, vector<p_d>, Compare> heap;
 </code> </code>
  • coding_cheat_sheet.1602117214.txt.gz
  • Last modified: 2020/10/08 00:33
  • by paul