/*
二分搜索算法
使用这些算法的前提:给定的序列为升序
lower_bound(beg,end,val)
lower_bound(beg,end,val,comp) //因对comp的作用机制不胜理解,暂不考虑使用
返回一个迭代器,表示的是键值为val的元素可以插入的第一个位置。
注意:C++Primer(第5版)中文版对该函数功能的描述有误!!!
upper_bound(beg,end,val)
upper_bound(beg,end,val,comp) //因对comp的作用机制不胜理解,暂不考虑使用
返回一个迭代器,表示的是键值为val的元素可以插入的最后一个位置。
lower_bound与upper_bound功能对比详解:
在序列里没有元素val的时候,两个元素的返回值是一样的。
1 2 4 5 这个序列,upper_bound(3)和lower_bound(3)都返回位置2(下标)
如果只有一个元素val,low返回那个元素的位置,而upper_bound返回那个元素的位置的后一个位置。
1 2 4 5 这个序列upper_bound(2)返回下标2而lower_bound(2)返回下标1
多个元素val,lower_bound返回那多个元素中的第一个的位置,upper_bound返回那多个元素中的最后一个的后一个位置。
1 2 2 4 5 这个序列 upper_bound(2)返回下标3的位置,lower_bound(2)返回下标1的位置。
注意:在一个升序里,如果所有元素都大于val,则upper_bound和lower_bound都返回begin。都小于val则返回end(越界了)。
*/
#include "stdafx.h"
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a1[] = { 1,2,4,5 };
printf("lower_bound a1 %d\n", lower_bound(a1, a1 + 4, 3) - a1);
printf("lower_bound a1 %d\n", upper_bound(a1, a1 + 4, 3) - a1);
int a2[] = { 1,2,4,5 };
printf("lower_bound a2 %d\n", lower_bound(a2, a2 + 4, 2) - a2);
printf("lower_bound a2 %d\n", upper_bound(a2, a2 + 4, 2) - a2);
int a3[] = { 1,2,2,4,5 };
printf("lower_bound a3 %d\n", lower_bound(a3, a3 + 5, 2) - a3);
printf("lower_bound a3 %d\n", upper_bound(a3, a3 + 5, 2) - a3);
return 0;
}
二分搜索算法
使用这些算法的前提:给定的序列为升序
lower_bound(beg,end,val)
lower_bound(beg,end,val,comp) //因对comp的作用机制不胜理解,暂不考虑使用
返回一个迭代器,表示的是键值为val的元素可以插入的第一个位置。
注意:C++Primer(第5版)中文版对该函数功能的描述有误!!!
upper_bound(beg,end,val)
upper_bound(beg,end,val,comp) //因对comp的作用机制不胜理解,暂不考虑使用
返回一个迭代器,表示的是键值为val的元素可以插入的最后一个位置。
lower_bound与upper_bound功能对比详解:
在序列里没有元素val的时候,两个元素的返回值是一样的。
1 2 4 5 这个序列,upper_bound(3)和lower_bound(3)都返回位置2(下标)
如果只有一个元素val,low返回那个元素的位置,而upper_bound返回那个元素的位置的后一个位置。
1 2 4 5 这个序列upper_bound(2)返回下标2而lower_bound(2)返回下标1
多个元素val,lower_bound返回那多个元素中的第一个的位置,upper_bound返回那多个元素中的最后一个的后一个位置。
1 2 2 4 5 这个序列 upper_bound(2)返回下标3的位置,lower_bound(2)返回下标1的位置。
注意:在一个升序里,如果所有元素都大于val,则upper_bound和lower_bound都返回begin。都小于val则返回end(越界了)。
*/
#include "stdafx.h"
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int a1[] = { 1,2,4,5 };
printf("lower_bound a1 %d\n", lower_bound(a1, a1 + 4, 3) - a1);
printf("lower_bound a1 %d\n", upper_bound(a1, a1 + 4, 3) - a1);
int a2[] = { 1,2,4,5 };
printf("lower_bound a2 %d\n", lower_bound(a2, a2 + 4, 2) - a2);
printf("lower_bound a2 %d\n", upper_bound(a2, a2 + 4, 2) - a2);
int a3[] = { 1,2,2,4,5 };
printf("lower_bound a3 %d\n", lower_bound(a3, a3 + 5, 2) - a3);
printf("lower_bound a3 %d\n", upper_bound(a3, a3 + 5, 2) - a3);
return 0;
}