c++ - 返回不同类型数组的最大元素的函数
问题描述
我有几个比较功能是这样的:
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。仍在试图找出原因,我感谢所有人说这不是最好的方法,但不幸的是,这是我必须这样做的方式。
解决方案
由于您被迫使用这些函数签名,因此这是处理它们的一种方法。
// 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;
}
推荐阅读
- python-3.x - 如何从以前的父目录调用模块?
- xamarin - 如何使用 AVPlayer 或 MPMoviePlayer 按文件路径(保存在照片库中)播放视频?-xamarin.ios
- c++ - 如何将 std::copy 用于内部具有值的结构数组
- javascript - 将类添加到 for 循环中的所有元素
- jenkins - Jenkins 脚本化管道 - 在阶段之间传递工件的多次执行
- facebook - 在 facebook ads api 中获取时间范围内的数据
- asp.net - Web 方法未在 ajax aspx Web 表单中调用
- jdbc - JDBC 类型真的很重要吗?
- c++ - 使用前导零进行字符串化
- python - 是否有可能通过`map_fn()`获得更高维度的张量?