自己按照stl实现了一个:

 

http://www.cplusplus.com/reference/algorithm/binary_search/ 这里有个注释,如何判断两个元素相同:

Two elements, a and bare considered equivalent if (!(a<b) && !(b<a))

lower_bound返回!(*it<val) ,所以binary_search 只要再判断 !(val<*it) 即可。

template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last, const T& val)
{
first = std::lower_bound(first,last,val);
return (first!=last && !(val<*first));
}

#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<iterator>
#include<sstream>//istringstream
#include<cstring> using namespace std; //return first element >= int * lowerbound(int *first, int* last, int value)
{
int* it;
int count=last-first;
int step;
while(count>0)
{
it=first;
step=count/2;
it+=step;
//it指向的<, ++后排除<
if(*it<value)
{
first=++it;
count-=step+1;
}
else//左边
count=step; }
return first;
} //return first element >
int* upperbound(int *first, int *last, int value)
{
int count=last-first;
int step;
int *it;
while(count>0)
{
step=count/2;
it=first+step;
//it指向 <= ,++后排除<=
if(!(value<*it))
{
first=++it;
count-=step+1;
}
else
{
count=step;
}
}
return first;
} int main()
{
int a[]={ 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 };
int *lb=lowerbound(a, a+sizeof(a)/sizeof(int), 4);
cout<<*lb<<endl; int *ub=upperbound(a, a+sizeof(a)/sizeof(int), 4);
cout<<*ub<<endl;
return 0;
}

最新文章

  1. mysql 批量导出建表语句 (视图,函数同理)
  2. IT关键词,发现与更新,点成线,线成面,面成体
  3. Aborting commit: &#39;XXX&#39; remains in conflict
  4. CSS控制文本自动换行
  5. SQL SERVER 中 GO 的用法2
  6. xamarin fivechess
  7. y combinator 做的一个调查_可以学习一下
  8. iOS中通知传值
  9. apache+mysql+php环境的手动搭建
  10. UIImageView 的contentMode属性应用
  11. 【EntityFramework 6.1.3】个人理解与问题记录(2)
  12. HDU4027 Can you answer these queries?(线段树 单点修改)
  13. GIT入门笔记(4)- GIT 安装
  14. deepin 开机进入 initramfs,无法开机
  15. maven项目-修复Plugin execution not covered by lifecycle configuration: org.codehaus.mojo:build-helper-maven-plugin:1.8:add-resource (execution: add-resource, phase: generate-resources) pom.xml报错
  16. zmq Poller
  17. Android手动控制软键盘的开启和关闭,判断软键盘是否显示;
  18. Python之路(第四篇):Python基本数据类型列表、元组、字典
  19. Android 沉浸式顶部
  20. Nagios自定义扩展

热门文章

  1. 【转】第一次使用Android Studio时你应该知道的一切配置
  2. Linux 平台下 YUM 源配置 手册
  3. Perfect Service
  4. HDU5739 Fantasia 树形dp + 点双缩点
  5. SQL你必须知道的-增删改查与约束
  6. CSS基础知识—【结构、层叠、视觉格式化】
  7. PHP实现分页:文本分页和数字分页
  8. 多校6 1001 HDU5793 A Boring Question (推公式 等比数列求和)
  9. Hadoop中FileSystem的append方法
  10. Python相关工具清单[持续更新]