您的位置:首页 > 其它

回调函数示例(一)

2013-06-08 20:09 246 查看
// callbackFun.h

#ifndef __CALLBACK_FUN_H__
#define __CALLBACK_FUN_H__

typedef unsigned char byte;
typedef int (__stdcall *CompareFunction)(const byte*, const byte*);		// define callback function type

// declare callback functions
int __stdcall CompareInts(const byte* velem1, const byte* velem2);		// callback function1
int __stdcall CompareStrings(const byte* velem1, const byte* velem2);	// callback function2

#endif


回调函数具体实现

// callbackFun.cpp

#include <string.h>
#include "callbackFun.h"

// implement callback functions
int __stdcall CompareInts(const byte* velem1, const byte* velem2) // callback function1
{
int elem1 = *(int*)velem1;
int elem2 = *(int*)velem2;
if(elem1 < elem2)
return -1;
if(elem1 > elem2)
return 1;
return 0;
}

int __stdcall CompareStrings(const byte* velem1, const byte* velem2) // callback function2
{
const char* elem1 = (char*)velem1;
const char* elem2 = (char*)velem2;
return strcmp(elem1, elem2);
}

测试程序

#include <iostream>
#include <string.h>
#include "callbackFun.h"

using namespace std;

void BubbleSort(byte* array,int size,int elem_size, CompareFunction cmpFunc)
{
for(int i=0; i < size; i++)
{
for(int j=0; j < size-1; j++)
{
//回调比较函数
if(1 == (*cmpFunc)(array+j*elem_size,array+(j+1)*elem_size))
{
//两个相比较的元素相交换
byte* temp = new byte[elem_size];
memcpy(temp, array+j*elem_size, elem_size);
memcpy(array+j*elem_size,array+(j+1)*elem_size,elem_size);
memcpy(array+(j+1)*elem_size, temp, elem_size);
delete [] temp;
}
}
}
}

int main(int argc, char* argv[])
{
int i;

// sort array by bubble sort algorithm
int array[] = {5432, 4321, 3210, 2109, 1098};
cout << "Before sorting ints with BubbleSort\n";
for(i = 0; i < 5; i++)
cout << array[i] << '\n';
BubbleSort((byte*)array, 5, sizeof(array[0]), &CompareInts);
cout << "After the sorting\n";
for(i=0; i < 5; i++)
cout << array[i] << '\n';
cout << endl;

// sort array by bubble sort algorithm
const char str[5][10] = {"estella", "danielle", "boomb", "bo", "angie"};
cout << "Before sorting strings with BubbleSort\n";
for(i = 0; i < 5; i++)
cout << str[i] << '\n';
BubbleSort((byte*)str, 5, 10, &CompareStrings);
cout << "After the sorting\n";
for(i = 0; i < 5; i++)
cout << str[i] << '\n';

return 0;
}

/*
运行情况:

D:\profile\Desktop\callbackFun>make
g++ -o a.exe a.cpp callbackFun.cpp

D:\profile\Desktop\callbackFun>a
Before sorting ints with BubbleSort
5432
4321
3210
2109
1098
After the sorting
1098
2109
3210
4321
5432

Before sorting strings with BubbleSort
estella
danielle
boomb
bo
angie
After the sorting
angie
bo
boomb
danielle
estella

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: