Binary search with returned index in STL?

前端 未结 6 1871
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 11:42

I need a binary search function.

I couldn\'t find any function in the standard library that will return the index of the found item, and if it wasn\'t found,

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 11:59

    int bin_search (ForwardIterator first, ForwardIterator last, const T& val)
    {
      ForwardIterator low;
      low = std::lower_bound(first,last,val);
      if(low!=last && !(val<*low)){
        return (low - first + 1);
      }else{
        return 0;
      }
    }
    

提交回复
热议问题