template <typename T>
struct MatchEqual {
bool operator()(T curIndex, T findIndex) const { return curIndex == findIndex; }
};
template <typename T>
struct MatchIsLeft {
bool operator()(T curIndex, T findIndex) const { return findIndex < curIndex; }
};
template <typename Container,
typename match = MatchEqual<typename Container::value_type>,
typename canLeft = MatchIsLeft<typename Container::value_type>,
typename constIter = typename Container::const_iterator,
typename valType = typename Container::value_type>
constIter binarySearchRange(constIter left, constIter right, valType index)
{
if (left > right) {
return left;
}
auto mid = left;
auto offset = (right - left) / 2;
if (0 == offset)
return left;
std::advance(mid, offset);
if (match()(*mid, index)) {
return mid;
}
if (canLeft()(*mid, index)) {
return binarySearchRange<Container, match, canLeft, constIter>(left, mid, index);
} else {
return binarySearchRange<Container, match, canLeft, constIter>(mid, right, index);
}
}
示例
std::vector<int> indexs{1, 3, 6, 7, 9};
auto begin = indexs.begin();
auto end = indexs.end();
auto findIndex = 6;
auto findIter =
BSearch::binarySearchRange<std::vector<int>>(begin, end, findIndex);
if(findIter != end)
std::cout<< "find\n";