我试图通过提供一个额外的参数来概括 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()
中使用它?
答案 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
}