问题:迭代器做函数模板参数

背景:
打算采用以迭代器的方式递归进行二分查找,具体代码如下:
该模板函数以该target元素的迭代器的方式返回

template <typename IterT,
        typename ValueT = typename std::iterator_traits<IterT>::value_type,
        typename Compare = const std::less<ValueT>>
IterT bsearch_r(IterT first,
            IterT last,
            ValueT target,
            Compare comp = Compare())
{
    
        IterT result = last;
        IterT mid = first + std::distance(first, last) / 2;
        if(comp(*mid, target))
        {
            first = mid + 1;
            bsearch_r(first, last, Compare());
        }
        else if(comp(target, *mid))
        {
            last = mid;
            //bsearch_r(first, last, Compare());
        }
        else
        {
            result = mid;
            return result;
        }
        return result;

}

调用代码如下:
计算距离第一个元素的距离:

template <typename VecT,
        typename T = typename VecT::value_type>
void test_bsearch(const VecT &test, T target)
{
    auto it = bsearch_r(test.begin(), test.end(), target);
    std::cout << std::distance(test.begin(), it)<< std::endl; 
}


int main()
{
    std::vector<int> test{0, 0, 1, 2, 3, 4, 4, 5, 5, 5, 5, 5, 6, 7};  // std::less<int>()

    test_bsearch(test, 5);                     

    return 0;

但报错,具体如下:

但还不知道是什么原因,特此记录
望各位大神不吝赐教

posted @ 2022-05-14 22:59  牛犁heart  阅读(94)  评论(0编辑  收藏  举报