Guest User

Function pointer example

a guest
Oct 1st, 2012
107
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <cstdio>
  2.  
  3.  
  4. void apply(void (*FUN)(int &), int *begin, int *end) {
  5.   for (int *p = begin; p != end; ++p) {
  6.     (*FUN)(*p);
  7.   }
  8. }
  9.  
  10. void apply2(void FUN(int &), int *begin, int *end) {
  11.   for (int *p = begin; p != end; ++p) {
  12.     FUN(*p);
  13.   }
  14. }
  15.  
  16. void apply3(void (*FUN)(int &), int *begin, int *end) {
  17.   for (int *p = begin; p != end; ++p) {
  18.     FUN(*p);
  19.   }
  20. }
  21.  
  22. void apply4(void FUN(int &), int *begin, int *end) {
  23.   for (int *p = begin; p != end; ++p) {
  24.     (*FUN)(*p);
  25.   }
  26. }
  27.  
  28. void negate(int &i) {
  29.   i = -i;
  30. }
  31.  
  32. void print(int &i) {
  33.   printf("%d ", i);
  34. }
  35. int main() {
  36.   int a[] = {10, 0, -10, 9};
  37.   const int N = sizeof(a) / sizeof(int);
  38.   apply(negate, a, a + N);
  39.   apply2(print, a, a + N);
  40.   printf("\n");
  41.  
  42.   apply3(negate, a, a + N);
  43.   apply4(print, a, a + N);
  44.   printf("\n");
  45.  
  46.   return 0;
  47. }
RAW Paste Data