回调函数示例(一)
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
*/
相关文章推荐
- 回调函数示例
- C语言回调函数用法示例
- Javascript中的回调函数和匿名函数的回调示例介绍
- VC之回调函数示例
- 回调函数 Callback function 的概念与程序示例
- 最小化的回调函数示例
- 回调函数示例
- 回调函数示例(一)
- 《GOF设计模式》—命令(COMMAND)—Delphi源码示例:参数化机制(回调函数)
- Visual C++ 回调函数示例
- linux使用定时器回调函数示例
- jquery序列化表单以及回调函数的使用示例
- 回调函数的使用示例
- 回调函数示例
- 【callback】js回调函数示例
- 转载:C++回调函数示例
- jquery序列化表单以及回调函数的使用示例
- C#中delegate实现回调函数示例
- C++回调函数示例
- 关于回调函数的一段示例代码