Advertisement
alfps

Function pointer example

Mar 30th, 2021
1,042
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <kickstart/all.hpp>        // https://github.com/alf-p-steinbach/kickstart
  2. using namespace kickstart::all;
  3.  
  4. #include <algorithm>
  5. #include <functional>
  6. using   std::sort,
  7.         std::reference_wrapper;
  8.  
  9. #define RANGE_OF( c ) std::begin( c ), std::end( c )
  10.  
  11. struct Student
  12. {
  13.     string      name;
  14.     int         birth_year;
  15.    
  16.     static auto ordered_by_name( const Student& a, const Student& b )
  17.         -> bool
  18.     { return (a.name < b.name); }
  19.  
  20.     static auto ordered_by_birth_year( const Student& a, const Student& b )
  21.         -> bool
  22.     { return (a.birth_year < b.birth_year); }
  23. };
  24.  
  25. template< class Order_func >
  26. void display( const vector<Student>& students, const Order_func order )
  27. {
  28.     vector<reference_wrapper<const Student>> ordered_students;
  29.  
  30.     for( const Student& student: students ) {
  31.         ordered_students.push_back( student );
  32.     }
  33.     sort( RANGE_OF( ordered_students ), order );
  34.     for( const auto student_ref: ordered_students ) {
  35.         out << student_ref.get().name << " " << student_ref.get().birth_year
  36.             << endl;
  37.     }
  38. }
  39.  
  40. auto main() -> int
  41. {
  42.     const vector<Student> students =
  43.     {
  44.         {"B", 2004 }, { "C", 2002 }, { "A", 2005 }, { "E", 2001 }, { "D", 2003 }
  45.     };
  46.     display( students, &Student::ordered_by_name );
  47.     out << endl;
  48.     display( students, &Student::ordered_by_birth_year );
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement