How to use function pointers and array of function pointers

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/feitianxuxue/article/details/7300291

How to use function pointers and array of function pointers

function pointers:

The function pointer contains the address of the function in memory. the array name is actually the address of the first element of the array in memory, and similarly, the function name is actually the starting address of the code in memory that performs the function task .

A function pointer can be passed to a function, returned from a function, saved in an array, given another function pointer, or called the underlying function.

Below we use the numerical algorithm accumulate to discuss the use of function pointers. Accumulate is a common STL mathematical algorithm.

Std::accumulate (V.begin (), V.end (), 0) is the sum of the elements in V starting from V.begin () until V.end () (but not including this position) in the range.

The fourth argument of the second version of this function is a general function that determines how the elements are summed. This general function must take two arguments and return a result. The first argument is the current value of and, and the second argument is the value of the current element that is summed in the sequence.

Many STL algorithms allow function pointers to be passed to the algorithm to help the algorithm perform tasks.

The following demo uses a function pointer to demonstrate the accumulate function.

1#include <iostream>2#include <vector>3#include <algorithm>//Copy Algorithm4#include <numeric>//Accumulate Algorithm5#include <functional>6#include <iterator>//Output iterators7 using namespacestd;8 9 //defines the Sumsquares function, which computes the square of the second argument value and adds the result to the first argument, returning the sum of the two. Ten intSumsquares (intTotalintvalue) One { A  returnTotal + value*value; - } - int_tmain (intARGC, _tchar*argv[]) the { -  Const intSIZE =Ten; -  intArray[size] = {1,2,3,4,5,6,7,8,9,Ten}; -vector<int> Integers (array,array+size);//element Copy +ostream_iterator<int> Output (cout," "); -  intresult; +cout<<"vector integers contains:\n"; A copy (Integers.begin (), integers.end (), output); at  -  //The accumulate function passes each element of the sequence it iterates to the Sumsquares function as a second argument -  //when the Sumsquares function is called for the first time, the first argument is the initial value of total (provided as the third argument of the accumulate, in this case, 0) -  //In all subsequent calls to the Sumsquares function, the first argument that is passed to it is the current and Sumsquares returned when the previous call was made.  -  //when accumulate ends, it returns the sum of the squares of all the elements in the sequence.  -result = Accumulate (Integers.begin (), Integers.end (),0, sumsquares);//call the accumulate function with a function pointer pointing to Sumsquares as the last argument in  -cout<<"\n\nsum of square of element in integers using" to<<"binary\nfuncion Sunsquare:"<<result; +  -cout<<Endl; theSystem"Pause"); *  return 0; $}

Operation Result:

function pointers differ from function return pointers:

For example:

Void selectionsort (int work[],const int Size,bool (*compare) (Int,int))

The parameter bool (*compare) (Int,int) appears in the function above Selectionsort

This parameter specifies a function pointer. The key bool indicates that the function being directed returns a bool value.

The text (*compare) represents the name of the function pointer (* indicates that the parameter compare is a pointer).

The text "(Int,int)" means that the function pointed to by compare accepts two shaping arguments.

The parentheses on either side of "*compare" are required, which means that compare is a function pointer.

If there is no parentheses, the declaration becomes BOOL *compare (int,int)

It declares a function that takes two integers as arguments and returns a pointer to the BOOL value.

Array of function pointers

A usage of a function pointer appears in the menu-driven system . For example, a program can prompt the user to enter an integer value to select an option in the menu. The user's choice can be the subscript of a function pointer array, and pointers in the array can be used to invoke functions.

The following demo provides a mechanical example that demonstrates the declaration and use of an array of function pointers. 3 functions are defined in the program: Function0, Function1, and function2, each with a single shape argument and no value returned.

1#include <iostream>2 using namespacestd;3 4 voidFunction0 (int);5 voidFunction1 (int);6 voidFunction2 (int);7 8 int_tmain (intARGC, _tchar*argv[])9 {Ten  void(*f[3])(int) = {Function0,function1,function2};//save these 3 function pointers in the array F One  A  intchoice; -  -cout <<"Enter A number between 0 and 2,3 to end:"; theCIN >>choice; -  -  //handling the user's choice -   while((Choice >=0) && (Choice <3)) +  { -   //call a function in the array F +(*f[choice]) (choice);//F[choice] Select a pointer in the array where the position is choice.  A                          //The pointer is dereferenced to invoke the function, and choice is passed as an argument to the function.  atcout <<"Enter A number between 0 and 2,3 to end:"; -CIN >>choice; -  } -  -cout <<"Program execution completed."<<Endl; -System"Pause"); in  return 0; - } to  + voidFunction0 (inta) - { thecout <<"You entered"<< a <<"So Function0 was called\n\n"; * } $ Panax Notoginseng voidFunction1 (intb) - { thecout <<"You entered"<< b <<"So Function0 was called\n\n"; + } A  the voidFunction2 (intc) + { -cout <<"You entered"<< C <<"So Function0 was called\n\n"; $}

Operation Result:

How to use function pointers and array of function pointers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.