轉載於:http://blog.csdn.net/tjpuacm/article/details/26389441
不加比較函數的情況:
- int a[]={0,1,2,2,3};
- printf("%d\n",lower_bound(a,a+5,2,cmp)-a);
- printf("%d\n",upper_bound(a,a+5,2,cmp)-a);
結果:2 4
lower的意義是對於給定的已經排好序的a,key最早能插入到那個位置
0 1 | 2 2 3 所以2最早插入到2號位置
upper的意義是對於給定的已經排好序的a,key最晚能插入到那個位置
0 1 2 2 | 3 所以2最晚插入到4號位置
加了比較函數:
- bool cmp(int a,int b)
- {
- return a<b;
- }
- int main()
- {
- int a[]={0,1,2,2,3};
- printf("%d\n",lower_bound(a,a+5,2,cmp)-a);
- printf("%d\n",upper_bound(a,a+5,2,cmp)-a);
- return 0 ;
- }
結果仍然是2 4 ,可以得出一個結論,cmp里函數應該寫的是小於運算的比較
如果加上了等號,lower和upper兩個函數功能就剛好反過來了:
- bool cmp(int a,int b)
- {
- return a<=b;
- }
- int main()
- {
- int a[]={0,1,2,2,3};
- printf("%d\n",lower_bound(a,a+5,2,cmp)-a);
- printf("%d\n",upper_bound(a,a+5,2,cmp)-a);
- return 0 ;
- }
結果是4 2
