简体   繁体   English

向量二元搜寻

[英]Binary search with a vector

I have a sorted vector V and I want to binary search the smallest index i for which V[i] <= target. 我有一个排序的向量V,我想对V [i] <=目标的最小索引i进行二进制搜索。 This is my current attempt but it isn't working right. 这是我目前的尝试,但无法正常工作。

int hi= L;
int lo= 1;
int mid  = (hi+lo)/2;
while (hi>lo+1){
    if (V[mid]>=target) hi=mid;
    else lo= mid;
    mid=(hi+lo)/2;
}
   auto s=v.begin();
   auto e=v.end();
   auto L = std::distance(s, e);

  while (L > 0)
{
  auto half = L/2;
  auto mid = s;
  std::advance(mid, half);
  if (*mid < target)
    {
      s = mid;
      ++s;
      L = L - half - 1;
    }
  else
    L = half;
}
  //s is your element !

Or why can't you use lower_bound for < target search :- 还是为什么不能将lower_bound用于< target搜索:-

#include<iostream>
#include<vector>
#include<algorithm>

typedef std::pair<int,int> mypair;

struct comp_pairs
{
   bool operator()( const mypair lhs, 
                    const int& rhs ) const 
   { return lhs.first < rhs; }
   bool operator()( const int& lhs, 
                    const mypair& rhs ) const 
   { return lhs<rhs.first; }
};

int main()        
{

std::vector<mypair> V;
V.push_back(std::make_pair(2,9));
V.push_back(std::make_pair(3,8));
V.push_back(std::make_pair(4,7));
V.push_back(std::make_pair(5,6));

int target =4;
  auto pos=std::lower_bound(V.begin(),V.end(),target,comp_pairs());

std::cout << "Position " << (pos- V.begin()) << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM