The aim of this example is to show how you can use user defined binary and unary predicate functions (not functors) and the bind2nd with the Standard Template Library. We will be using a vector for this purpose, but it applies for all containers. In this example we use a class that represents a complex number. Complex numbers are compared by squaring both real and imaginary components and adding them together.
Line 50 Use our user defined ValueGreaterThan20 unary predicate in the find_if
Line 54 Use the ValueGreaterThan Binary predicate, but we use bind2nd to make it unary.
Line 57 Use the binary predicate SortValueGreaerThan in the sort function.
Do not forget to use ptr_fun when passing the function pointers to the bind2nd. Ptr_fun takes a function pointer as its argument and returns a function pointer adapter. If you forget you will get some errors such as below
../include/c++/backward/binders.h:138: error: 'bool ()(ComplexNumber, int)' is not a class, struct, or union type
1. #include <vector> 2. #include <functional> 3. #include <algorithm> 4. #include <iostream> 5. 6. using namespace std; 7. 8. template <class Operation, class T> 9. bool ninjax (const Operation& op, const T& x) 10. { 11. return true; 12. } 13. 14. class ComplexNumber{ 15. public: 16. ComplexNumber(int r, int i): real(r), imaginery(i){} 17. int real; 18. int imaginery; 19. }; 20. 21. //Unary predicate 22. bool ValueGreaterThan20(ComplexNumber c){ 23. return c.imaginery*c.imaginery+c.real*c.real > 20*20; 24. } 25. 26. //Binary predicate 27. bool ValueGreaterThan(ComplexNumber c, int i){ 28. cout<<c.imaginery<<endl; 29. return c.imaginery*c.imaginery+c.real*c.real > i*i; 30. } 31. 32. //Binary predicate 33. bool SortValueGreaterThan(ComplexNumber c, ComplexNumber b){ 34. cout<<c.imaginery<<endl; 35. return c.imaginery*c.imaginery+c.real*c.real > b.imaginery*b.imaginery+b.real*b.real; 36. } 37. 38. int main(){ 39. 40. vector<ComplexNumber> complexNumbersVec; 41. 42. complexNumbersVec.push_back(ComplexNumber(5,5)); 43. complexNumbersVec.push_back(ComplexNumber(10,15)); 44. complexNumbersVec.push_back(ComplexNumber(15,5)); 45. 46. complexNumbersVec.push_back(ComplexNumber(10,20)); 47. 48. //Using bind2nd with user defined unary predicate function 49. vector< ComplexNumber >::iterator location = 50. find_if(complexNumbersVec.begin(), complexNumbersVec.end(), ValueGreaterThan20); 51. 52. //Using bind2nd with user defined binary predicate function 53. vector< ComplexNumber >::iterator location2 = 54. find_if(complexNumbersVec.begin(), complexNumbersVec.end(), bind2nd(ptr_fun(ValueGreaterThan), 0)); 55. 56. //Using sort with user defined binary predicate funcion 57. sort (complexNumbersVec.begin(), complexNumbersVec.end(), SortValueGreaterThan); 58. 59. for (location=complexNumbersVec.begin(); location!=complexNumbersVec.end(); location++) 60. cout << " " << location->real <<", "<<location->imaginery<<"i"<<endl; 61. 62. } |
