gpt4 book ai didi

c++ - 转换为模板

转载 作者:行者123 更新时间:2023-11-28 01:48:46 25 4
gpt4 key购买 nike

我想知道我该如何做这样的事情?使用 template<typename T>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;
}

最佳答案

Typedef 不能是模板。 C++11 using但是,别名可以是:

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

C++11 之前的解决方法是创建一个具有 type 的模板结构类型定义:

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

然后引用为 typename cmp_func<int>::type例如。

关于c++ - 转换为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43812141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com