2012-04-21 62 views
1
template <class T> 
bool cmp(const T &a, const T &b){ 
    return a <= b; 
} 

template <class T> 
void bubble_sort(T tablica[], int size, bool compare(T,T)){ 
    bool change = true; 

    while(change){ 
     change = false; 
     for(int i=0; i < size-1; ++i){ 
      if(compare(tablica[i+1], tablica[i])){ 
       zamien(tablica[i+1], tablica[i]); 
       change = true; 
      } 
     } 
    } 
} 

它不工作,我有錯誤:排序與自己的模板陣列,C++比較功能

'void bubble_sort(T [],int,bool (__cdecl *)(T,T))' : 
could not deduce template argument for 'T []' from 'int [10]' 
'void bubble_sort(T [],int,bool (__cdecl *)(T,T))' : 
cannot use function template 'bool cmp(const T,const T)' as a function argument' 

但是當我更換一個CMP功能:

bool cmp(const int a, const int b){ 
    return a <= b; 
} 

一切正常。 如何更改我的cmp函數以使用模板?

+0

C++沒有泛型,它有模板。這兩者可能看起來一樣,但他們的工作方式根本不同。 – Jasper 2012-04-21 14:36:55

+0

當我將'compare(T,T)'改爲'compare(const T&,const T&)'並將'zamien'行註釋掉時編譯。至少當數字不同時,將'zamien'改爲'std :: swap'會產生正確的結果。 – chris 2012-04-21 14:40:34

+0

@Jasper,但你使用模板來做泛型編程:-) – juanchopanza 2012-04-21 14:44:39

回答

2

的問題是,「比較」函數參數bubble_sort預計的類型爲:

bool compare(T,T) 

雖然「CMP」函數的類型爲:

bool compare(const T&,const T&) 

爲了解決它,修改「比較」參數的類型:

template <class T> 
void bubble_sort(T tablica[], int size, bool compare(const T&,const T&)){ 
    /* ... */ 
} 
+0

我仍然有這樣的錯誤:'void bubble_sort(T [],int,bool (__cdecl *)(const T&,const T&))':當我想使用它時,無法從'int [10]'推導'T []'的模板參數:bubble_sort(tab,size,cmp) ,其中tab [] = {0,1,2,3,4,5,6,7,8,9}。 – 2012-04-21 15:18:37

+0

這爲我編譯︰http://ideone.com/6b13z – mfontanini 2012-04-21 15:20:10

+0

好吧,在ideone它的作品完美,但是當我嘗試在MS Visual 2010中編譯它時,我有錯誤。 – 2012-04-21 16:55:57

0

這就是我如何並與此問題:

int (*cmp_int)(int,int) = compare<int>; 
bubble_sort(in, 5, cmp_int); 

現在它應該在MS Visual中正常工作。