Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 函数,该函数返回不同类型数组的最大元素_C++_C++11_Max - Fatal编程技术网

C++ 函数,该函数返回不同类型数组的最大元素

C++ 函数,该函数返回不同类型数组的最大元素,c++,c++11,max,C++,C++11,Max,我有两个比较函数,如下所示: int greater_than_int(const void *a, const void *b) { if (*(int *)a > *(int *)b) return 1; return 0; } const void* max(const void *base, size_t members, size_t size, int (*compar)(const void *, const void *)) {

我有两个比较函数,如下所示:

int greater_than_int(const void *a, const void *b) {
    if (*(int *)a > *(int *)b) return 1;
    return 0;
}
const void* max(const void *base, size_t members, size_t size,
              int (*compar)(const void *, const void *)) {

char *base_ptr = (char *) base;
char max = *base_ptr;
for(int i = 1; i < nmemb; i++) {
    if (compar(&(*(base_ptr + i*size)), &max) != 0) {
        max = *(base_ptr + i*size);
    }
}
return &max;

}
一个max函数是这样的:

int greater_than_int(const void *a, const void *b) {
    if (*(int *)a > *(int *)b) return 1;
    return 0;
}
const void* max(const void *base, size_t members, size_t size,
              int (*compar)(const void *, const void *)) {

char *base_ptr = (char *) base;
char max = *base_ptr;
for(int i = 1; i < nmemb; i++) {
    if (compar(&(*(base_ptr + i*size)), &max) != 0) {
        max = *(base_ptr + i*size);
    }
}
return &max;

}
当我尝试用GealErthAthixIt运行这个函数时,我得到了一些无意义的结果,因为我还是C++的新手,我不知道为什么。任何帮助都将不胜感激


编辑:我对代码做了一些更改,但现在它总是将max返回为0。仍在试图找出原因,我很感激所有人说这不是最好的方法,但不幸的是,这是我必须这样做的方式。

因为你不得不处理这些函数签名,这里有一种处理方法

// I suggest changing this to `bool`, but you can leave it as `int` if you must
bool greater_than_int(const void *a, const void *b) {
    // no need for `if(...)` - just return the result of the comparison
    return *static_cast<const int*>(a) > *static_cast<const int*>(b);
}

我不是说你应该使用它,但是看看维基。这很鼓舞人心。可能实现的部分很棒!99.99%的时间空洞*或const空洞*用于C++代码,它是自动错误的。现代C++从来都不需要这样。使用此类强制转换的唯一时间是与C库接口。使用void*会破坏C++内置的强类型系统,并成为难以诊断的bug的肥沃土壤。像这个。在摆脱所有这些问题的过程中,用适当的、强类型的代码或模板替换它,很可能会找到bug的潜在根源。编译器几乎可以保证为您找到潜在的bug,因为它有实际的类型可以使用。我必须使用const void*-不,为什么?即使是你的老师也不能激励你。任何人都不应该声明一个带有签名的函数。这纯粹是浪费时间。。。。如果所有这些C风格的计算都被适当的基于C++的迭代器和容器逻辑所取代,编译器就会自动完成这些计算,并且正确地完成它们。感谢您的回复,我如何正确地调用它?我试着这样做:mymaxarr_int,9,sizeofint,greater_than_int,其中arr_int是一个数组,我试图找到最大值,9是其中的元素数,但当我运行时,我得到如下结果:0xffffcc18@WholesomeGhost不客气。你是说?就这样!非常感谢。@healthomeghost太好了,不客气!