use*_*274 35 c++ sorting search vector find
我查看了find和binary_search,但find没有利用向量排序的事实,而binary_search只返回true或false,而不是它找到值的位置.有什么功能可以让我两全其美吗?
Ste*_*ard 41
std :: lower_bound会为你做这件事.它位于binary_search顶部的等效行为部分.
template<class T, class U>
bool contains(const std::vector<T>& container, const U& v)
{
auto it = std::lower_bound(
container.begin(),
container.end(),
v,
[](const T& l, const U& r){ return l < r; });
return it != container.end() && *it == v;
}
Run Code Online (Sandbox Code Playgroud)