fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. struct node{
  7. string val1;
  8. string val2;
  9. vector<node *> connectedNodes;
  10. };
  11.  
  12. int compareNode(node a,node b){
  13. //describe the compare
  14. return a.val2.compare(b.val2); // or any other code
  15. }
  16.  
  17. template <class T>
  18. class PQueue {
  19. protected:
  20. // this declares a private member named compareFunction of type pointer to a function which takes 2 T parameters and returns a int. Note that all the parenthesis are mandatory
  21. int (*compareFunction)(T, T);
  22.  
  23. public:
  24.  
  25. PQueue (int (*compareFunctionParameter)(T, T)) : compareFunction(compareFunctionParameter) {
  26. // this constructor receives a pointer to function and initializes it's member to that pointer. If the constructor initialization list confuses you, you can read 'compareFunction = compareFunctionParameter '
  27. }
  28.  
  29. int someMethod() {
  30. // call the function through the pointer you have:
  31. node n1, n2;
  32. n1.val1 = "node1_val1";
  33. n1.val2 = "zzz";
  34.  
  35. n2.val1 = "node2_val1";
  36. n2.val2 = "aaa";
  37. return compareFunction(n1, n2);
  38. }
  39. };
  40.  
  41. int main() {
  42. PQueue<node> pq(compareNode);
  43. cout << pq.someMethod() << endl;
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
1