2017-05-05 56 views
-3

我想知道我該如何做這樣的事情?使用template<typename T>typedef我如何使用typedef模板

template <typename T> 
typedef bool (*cmp_func)(T i0, T i1); // <- syntax error here 

我想排序模板類型的項目。

#include <cstdlib> 
#include <iostream> 
#include <iomanip> 
#include <string> 
#include <cmath> 
#include <ctime> 

using namespace std; 

typedef bool (*cmp_func)(int i0, int i1); 


template<typename T> 
void print_array(int n, T *x) 
{ 
     cout << "["; 
     for (int i = 0; i < n; ++i) { 
       cout << setw(3) << x[i]; 
     } 
     cout << " ]\n"; 
} 

template <typename T> 
bool less_than(T i0, T i1) { return i0 < i1; } 

template <typename T> 
bool greater_than(T i0, T i1) { return i0 > i1; } 

template <typename T> 
bool is_sorted(int n, T *x, cmp_func cmp) 
{ 
     for (int i = 1; i < n; ++i) 
       if ((*cmp)(x[i], x[i-1])) 
         return false; 

     return true; 
} 

    template <typename T> 
void exchange(T* x, int i, int j) 
{ 
     T t = x[i]; 
     x[i] = x[j]; 
     x[j] = t; 
} 


template <typename T> 
void insertion_sort(T *x, int l, int r, cmp_func cmp) 
{ 
     for (int i = l+1; i <= r; ++i) { 
       for (int j = i; j > l; --j){ 
         if ((*cmp)(x[j], x[j-1])) 
           exchange(x, j, j-1); 
        cout << " "; 
        print_array(r-l+1, x+l); 
       } 
     } 
} 

template <typename T> 
void insertion_sort2(T *x, int l, int r, cmp_func cmp) 
{ 
     for (int i = r; i > l; --i) 
       if ((*cmp)(x[i], x[i-1])) 
         exchange(x, i, i-1); 

     for (int i = l+2; i <= r; ++i) { 
       int j = i; 
       int v = x[i]; 
       while((*cmp)(v, x[j-1])) { 
         x[j] = x[j-1]; 
         --j; 
       } 
       x[j] = v; 

       cout << " "; 
       print_array(r-l+1, x+l); 
     } 
} 

template <typename T> 
void fill_random(T n, T *x) 
{ 
     const int M = 100; 

     srand(time(0)); 

     for (int i = 0; i < n; ++i) 
       x[i] = rand() % M; 
} 

int main(int argc, char **argv) 
{ 
     const int N = 10; 
     int x[N]; 
     fill_random(N, x); 
     print_array(N, x); 

     insertion_sort(x, 0, N-1, &less_than); 
     print_array(N, x); 

     if (is_sorted(N, x, &less_than)) 
       cout << "SORTED\n"; 
     else 
       cout << "NOT SORTED\n"; 

     return EXIT_SUCCESS; 
} 
+1

請您詳細說明一下嗎?我不清楚你在問什麼。 – NathanOliver

+2

C++/CLI與此無關。不要垃圾標籤。 – crashmstr

回答

2

由於C++ 11可以使用using關鍵字:

template <typename T> 
using cmp_func = bool (*)(T i0, T i1); 

這樣做的一個C++ 03友好的方式是使用struct

template <typename T> 
struct cmp_func 
{ 
    typedef bool (*type)(T i0, T i1); 
};