[c++] Function pointer with function call.

為了怕忘記,只好手動筆記了。:P

Source code is here.


/* Usage: To implement a function pointer with asc() , desc()
* Author: Allen (allen501pc@hotmail.com)
* Date: 04/26/2009
* Output:
* Sorted number list.
*/
#include
using namespace std;

bool asc(int *,int *);
bool desc(int *,int *);

void mysort(int *,size_t,bool (*)(int *, int *));
void print(int [],size_t);
int main(int argc,char * argv[])
{
int iarray[10]={3,4,7,9,8,2,5,1,6,10};
mysort(iarray,10,desc); // sort by desc
print(iarray,10);
mysort(iarray,10,asc); // sort by asc
print(iarray,10);
}

bool asc(int * a,int * b)
{
int temp_int;
if(*a>*b)
{
temp_int=*a;
*a=*b;
*b=temp_int;
return true;
}
return false;
}

bool desc(int * a,int * b)
{
int temp_int;
if(*a<*b)
{
temp_int=*a;
*a=*b;
*b=temp_int;
return true;
}
return false;
}

void mysort(int * iarray,size_t size,bool (*func)(int *,int *))
{
size_t i;
bool swapped;
do
{
swapped=false;
for(i=0;i
This entry was posted in 程式設計. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *