将一个模板回调函数传递给另一个模板函数

4

我试图将我的回调函数comp传递给模板函数quickSortR,但是出现了以下错误:

2 IntelliSense: no instance of function template "quickSortR", corresponding to the list of arguments"

当我取消代码顶部的注释时,我得到另一个错误列表。因此,我认为问题在于回调函数的使用不正确。

#include<stdio.h>

/* 
 template<class T> 
 int comp(const void*, const void*);
 template<class T>
 void quickSortR(T* a, long N, int comp(const void*,const void*));
 Here is my instance. I commented it. 
*/ 


template<class T> 
int comp(const void* a, const void* b)
{

    return (*(T*)a - *(T*)b);
}

template<class T>
void quickSortR(T* a, long N, int comp(const void*,const void*)) {


    long i = 0, j = N;      
    T temp, p;

    p = a[ N>>1 ];      

    do {
        while ( !comp(*a[i],*p) ) i++;
        while ( comp(*a[j],*p) ) j--;

        if (i <= j) {
            temp = a[i]; a[i] = a[j]; a[j] = temp;
            i++; j--;
        }
    } while ( i<=j );


    if ( j > 0 ) quickSortR(a, j, comp);
    if ( N > i ) quickSortR(a+i, N-i, comp);
}

int main() {
    int n;
    int m[10] = {1,-3,5,-100,7,33,44,67,-4, 0};

    //problem is on this line
    quickSortR<int>(m, 10, comp);

    for (n=0; n<10; n++)
        printf ("%d ",m[n]);

    return 0;
}

在计算机中,是否需要使用void*?或者在快速排序中呢? - Koushik Shetty
1个回答

3

以下是需要翻译的内容:

有一些问题需要你修复才能编译。

A. 替换

quickSortR<int>(m, 10, comp);

使用

quickSortR<int>(m, 10, comp<int>);

B. 另一种
while ( !comp(*a[i],*p) ) i++;
while ( comp(*a[j],*p) ) j--;

替换为

while ( !comp(&a[i],&p) ) i++;
while ( comp(&a[j],&p) ) j--;
< p >由于comp是采用指针,而不是值。请仔细检查此逻辑。

但是,这只能解决编译器错误,而无法解决逻辑错误。


@dbasic 谢谢你的 B,但是 A 出现了“类型'int'不需要”和“comp: 未声明的标识符”错误。 - D3migod
可能你不需要 A,但编译器错误应该已经解决了。我在 codepad.org 上测试过这个问题。 - doptimusprime
我在这里运行代码http://codepad.org/quyqUELA,输出不正确,但编译器错误已经消失。 - doptimusprime
@dbasic 错误在我的编译器上也消失了!谢谢!我想提高你的声望,但我自己的声望不够,抱歉。 - D3migod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接