如何使用自定义比较器测试相等性?

时间:2017-05-31 10:22:09

标签: c++ templates

我试图通过提供一个额外的参数来概括 Binary Seach 的实现: Custom Comparator

template <typename T, typename It>  // Not sure if right !
struct LessCmp
{
    bool operator()(const T& lhs, It rhs)
    {
        return lhs < *rhs;
    }
};

template <typename It, typename T, typename Cmp>
bool binary_search(It begin, It end, const T& target, Cmp op) // Not sure if right !
{
    while (begin != end)
    {
        auto offset  = std::distance(begin, end);
        It middle = begin;
        std::advance(middle, offset / 2);

        if (/* how ? */)             // target == middle
        {
            return true;
        }
        else if (op(target, middle)) // target < middle
        {
            end = middle;
        }    
        else                         // target > middle
        {
            begin = middle;
            std::advance(begin, 1);
        }
    } 

    return false
}

如何使用LessCmp执行相等测试?如何实施LessCmp以便在binary_seach()中使用它?

1 个答案:

答案 0 :(得分:1)

假设op定义了超过T的严格总订单。

if(op(target, middle))
{
     // target is less than middle
}
// target could be equal or greater than middle
// if middle is less than target, then target is greater
else if (op(middle, target))
{
    // target is greater than middle
}
else
{
    // target is equal to middle
}