首页 > 解决方案 > 返回不同类型数组的最大元素的函数

问题描述

我有几个比较功能是这样的:

int greater_than_int(const void *a, const void *b) {
    if (*(int *)a > *(int *)b) return 1;
    return 0;
}

和一个像这样的 max 函数:

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;

}

当我尝试运行这个函数时,greater_than_int我得到了无意义的结果,因为我对 C++ 还是很陌生,我不知道为什么。任何帮助,将不胜感激。

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

标签: c++c++11max

解决方案


由于您被迫使用这些函数签名,因此这是处理它们的一种方法。

// 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);
}

然后,实际max函数存在一些问题,您定义max为 achar而不是指针等max可以保留为 a,const void*因为您不需要对其执行任何指针算术运算。我将base其用作指向下面最大元素的指针。

#include <iterator> // std::next, std::advance

const void* max(const void *base, size_t nmemb, size_t size,
                bool (*compar)(const void*, const void*))   // note: bool here too
{
    if(nmemb) {
        // no need to cast away const:
        auto current = static_cast<const char*>(base);
        auto end = std::next(current, nmemb * size);

        for(std::advance(current, size); current != end; 
            std::advance(current, size))
        {
            if(compar(current, base)) base = current;
        }
    }
    return base;
}

演示


推荐阅读