[关闭]
@scrolllock 2018-09-30T06:01:02.000000Z 字数 936 阅读 337

C++ lower_bound和upper_bound

学习笔记 C++STL


https://www.zybuluo.com/scrolllock/note/1279274


在一个有序容器的前闭后开的区间中,二分查找某个某个数的上下界位置
查找第一个的位置
查找第一个的位置
如图

对于数组的测试代码:

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. int a[] = {1, 2, 2, 3, 4, 4, 5, 5, 5, 6, 7};
  6. for (int i = 0; i <= 10; i ++) printf("a[%d] = %d\n", i, a[i]);
  7. printf("\n");
  8. int pos;
  9. pos = lower_bound(a, a + 10 + 1, 5) - a;
  10. printf("lower_bound(a , a + 10 + 1, 5) - a : %d\n", pos);
  11. pos = lower_bound(a + 1, a + 10 + 1, 5) - a;
  12. printf("lower_bound(a + 1, a + 10 + 1, 5) - a : %d\n", pos);
  13. pos = lower_bound(a + 1, a + 10 + 1, 5) - a;
  14. printf("lower_bound(a + 1, a + 10 + 1, 0) - a : %d\n", pos);
  15. pos = upper_bound(a + 1, a + 10, 5) - a;
  16. printf("upper_bound(a + 1, a + 10 + 1, 5) - a : %d\n", pos);
  17. pos = upper_bound(a + 1, a + 10, 8) - a;
  18. printf("upper_bound(a + 1, a + 10 + 1, 8) - a : %d\n", pos);
  19. return 0;
  20. }

输出:

  1. a[0] = 1
  2. a[1] = 2
  3. a[2] = 2
  4. a[3] = 3
  5. a[4] = 4
  6. a[5] = 4
  7. a[6] = 5
  8. a[7] = 5
  9. a[8] = 5
  10. a[9] = 6
  11. a[10] = 7
  12. lower_bound(a , a + 10 + 1, 5) - a : 6
  13. lower_bound(a + 1, a + 10 + 1, 5) - a : 6
  14. lower_bound(a + 1, a + 10 + 1, 0) - a : 6
  15. upper_bound(a + 1, a + 10 + 1, 5) - a : 9
  16. upper_bound(a + 1, a + 10 + 1, 8) - a : 10
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注