C++中二分法之upper_bound()、lower_bound、binary_search()函数

前言

  1. 数组、容器vector都适用,在头文件"algorithm"中
  2. 下面的例子是针对容器的,注意返回的是距离元素3最近的指针it,输出的是*it结果为元素4,假如我想得到位置而非具体的元素应该怎么办呢?这里有一个指针偏移的技巧,只需要减去起始位置的指针即可
#include<iostream> 
#include<vector> 
#include<algorithm> 
using namespace std; 
vector<int> v; 
int main() 
{ 
    for (int i = 1; i < 4; i++) 
        v.push_back(2 * i);//注意此时v中的元素本身就是有序的 
    vector<int>::iterator it = lower_bound(v.begin(), v.end(), 3); 
    cout << *it << endl; 
    return 0; 
} 
  1. 下面中的例子这里给出:
#include<iostream>
#include<algorithm>
#include<vector>
int test[11] = {1, 1, 3, 3, 6, 7, 8, 8, 8, 9, 10};
using namespace std;
int main(){
	int pos1 = lower_bound(test, test+11, 8) - test;
	int pos2 = upper_bound(test, test+11, 8) - test;
	int pos3 = lower_bound(test, test+11, 5) - test;
	int pos4 = upper_bound(test, test+11, 5) - test;
	bool a = binary_search(test, test+11, 5);
	bool b = binary_search(test, test+11, 3);
	cout << "pos1: " << pos1 << endl;
	cout << "pos2: " << pos2 << endl;
	cout << "pos3: " << pos3 << endl;
	cout << "pos4: " << pos4 << endl;
	cout << "a: " << a << endl;
	cout << "b: " << b ;
	return 0;
}

输出结果:

一、upper_bound(起始地址,结束地址,要查找的数值)

  1. 功能:返回数组或容器中大于指定元素的下标(使用指针偏移技巧)或数值。
  2. 例子见前言,仔细思考。

二、lower_bound(起始地址,结束地址,要查找的数值)

  1. 功能:返回数组或容器中大于等于指定元素的下标(使用指针偏移技巧),如果出现相同的元素恰是指定元素即返回第一个等于元素的下标。
  2. 例子见前言,仔细思考。

三、binary_search(起始地址,结束地址,要查找的数值)

  1. 功能:查看数组或容器中指定元素是否存在,bool类型,存在返回1,否则返回0。
  2. 例子见前言,仔细思考。
posted @ 2019-11-14 16:29  睿晞  阅读(330)  评论(0编辑  收藏  举报