【问题标题】:generic binary search in c++C ++中的通用二进制搜索
【发布时间】:2012-11-30 10:03:48
【问题描述】:

我想写一个模板二分搜索算法,它可以使用任意比较器在模板类型QList中搜索模板类型元素,像这样:

template<typename T,typename compare_less>
static int binary_search(QList<T>* list, T target) {
    int low = 0;
    int high = list->count()-1;
    while (low <= high) {
        int middle = low + (high - low)/2;
        if (compare_less(*target, *list[middle]))
            high = middle - 1;
        else if (compare_less(*list[middle],*target))
            low = middle + 1;
        else
            return middle;
    }
    return low;

}

现在我如何才能正确实现它以使其与 QDateTime* 模板参数一起使用?我想这样调用函数:

int index = binary_search<QDateTime*, ???>(dateTimeList,date);

dateTimeList 是 QList 类型,date 是 QDateTime* 类型,我真的不知道在问号位置写什么。

有人可以帮助我正确实现算法并告诉我如何使用这些参数调用算法吗?

【问题讨论】:

    标签: c++ templates search binary


    【解决方案1】:

    如果Qt documentation 有效,则您不必执行任何操作。只需将 std::binary_search 与列表的 .begin() 和 .end() 一起使用,如果需要实现比较器,请执行此操作并将其传递给 STL 算法。

    【讨论】:

    • 问题出在afaik,如果没有找到元素,std::binary_search 返回-1,但我想返回索引,元素应该插入其中。
    • 所以使用 std::lower_bound (cplusplus.com/reference/algorithm/lower_bound)。如果您不想插入重复项,则可能需要添加相等性测试,但它会为您提供所需的内容。
    • 感谢您的建议。现在我尝试使用 std::lower_bound,但编译器抱怨说,lower_bound 不是 std 的成员。我包括了“使用命名空间标准;”一开始。可能是什么问题?
    • 谢谢,这就是我正在寻找的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2017-03-28
    • 2013-12-12
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多