回调函数示例(一)

104 篇文章 0 订阅
88 篇文章 0 订阅
// 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

*/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值