[英]How to replace function calls with array of #define in C
I am trying to compare different sorting algorithms in one loop.我试图在一个循环中比较不同的排序算法。 I have #defined function calls in a string array, but it doesn't call the functions as intended.
我在字符串数组中有#defined 函数调用,但它没有按预期调用函数。 What could be the problem?
可能是什么问题呢?
function calls array:函数调用数组:
const char sorts[][30] = {"bubbleSort(arr, size)", "quickSort(arr, 0, size-1)", "insertionSort(arr, size)",
"selectionSort(arr, size)", "mergeSort(arr, 0, size)"};
Calling functions using array:使用数组调用函数:
for(int i = 0; i < NUMBER_OF_SORTS; ++i) {
sorts[i];
}
I am sure there is a working way, thanks for help in advance.我确定有一种可行的方法,在此先感谢您的帮助。
First, declare a type to represent a sorting function (supposing your sorting functions accept arrays of integers):首先,声明一个类型来表示排序函数(假设您的排序函数接受整数数组):
typedef void (SORTING_FUNCTION)(int*, size_t);
Then, define an array of pointers to your sorting functions (here, hungarian notation for the C language would merely propose snake case, bubble_sort , while for C++
it would be camel case bubbleSort , as you did):然后,定义一个指向您的排序函数的指针数组(在这里,C 语言的匈牙利表示法将仅建议蛇形大小写bubble_sort ,而对于
C++
它将是驼峰大小写bubbleSort ,就像您所做的那样):
SORTING_FUNCTION *sort[] =
{
bubbleSort,
quick_sort_wrapper,
insertionSort,
selectionSort,
mergeSort
};
and call it so:并这样称呼它:
sort[i](array, size);
taking i
from 0 up to 4 in this case.在这种情况下,
i
从 0 到 4。
EDIT: If some sorting function takes additional arguments, for example quickSort
, then instead of calling quickSort
directly, you define a wrapper function quick_sort_wrapper
which will have a SORTING_FUNCTION signature and this function will call quickSort
, passing it an additional argument, apart from array
and size
.编辑:如果某些排序函数需要额外的参数,例如
quickSort
,那么您可以定义一个包装函数quick_sort_wrapper
,而不是直接调用quickSort
,它将具有SORTING_FUNCTION签名,并且该函数将调用quickSort
,向它传递一个额外的参数,除了array
和size
。
This is probably the best approach for a beginner, leaving yourself the best opportunity to get help from the compiler.对于初学者来说,这可能是最好的方法,让您自己有最好的机会从编译器那里获得帮助。
switch (i) {
case 0:
bubbleSort(arr, size);
break;
case 1:
quickSort(arr, 0, size-1);
break;
case 2:
insertionSort(arr, size);
break;
case 3:
selectionSort(arr, size);
break;
case 4:
mergeSort(arr, 0, size);
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.