Function as a parameter on C++

Hi, today let come talk about function pointer. The reason I bring it up is mainly the technique itself would give out a illusion which only apply on scripting language as JavaScript. However it does exist on C++, surprising conversion while working on a real-world project.

Also it’s not exist in most intro level of C++ tutorial on Web and my three years computer science degree, until one day I search it on google by curiosity.

it’s a technique to  pass a function as a method parameter into a function call. Concept is simple, but why you need this? Hope the example listed below can give you more clue about the usage.

Following is a snap shot of a side project which I currently working on, it’s call Uni algorithm, basically provide variety choice of sorting algorithm for user to pick. As the nature of algorithm, of course testing need to be take place right? In order to guarantee the correctness.

Here is the function call:
660b3e48-d9ba-4ab5-bf86-1516d5ddb566

And testing call:
screen-shot-2016-10-28-at-6-50-56-pm

As you may notice this function first sort all above 4 sets of arrays then pass it to compare with the correct answer on check( ) method call. The whole piece of code look tidy, clean and straight forward right? However the problem came in with I have to test heaps of function, certainly copy and paste is not way of doing this. Because the whole file look so redundant same pieces of checking going again and again.

Is there have any way of improve this?

Encapsulate sorting method call into check function? Then four lines of call can be skipped easily further more testing can be done on one single line rather than two steps (sorting , then testing ) at the moment.  So I come out with a newer version of check function call check_new.

 

3
4

Nothing special, but the latest version sort income_ing array by given choice of function. Here it provide a extra flexibility of function call choice, as all sorting method in Uni algorithm have the same interface, so technically should be able to feed it all sorting method for testing. Then total line that save gonna be far more than 4 lines.

Improved version of bubble sort testing:

6

5

So all the check_new is not limited into bubble sort, can be apply into other method which have the same interface. Obviously passing function call as a parameter, can make function call more generic and flexible. By the way the full versos of the source can be found on: https://github.com/andykhk/Uni_algorithm

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s