OSDN Git Service

Added an example of lower_bound into the introduction of STL algorithms.
authorsbofgayschool <1532422769@qq.com>
Mon, 9 Nov 2020 06:55:16 +0000 (14:55 +0800)
committersbofgayschool <1532422769@qq.com>
Mon, 9 Nov 2020 06:55:16 +0000 (14:55 +0800)
docs/lang/csl/algorithm.md

index c803098..01ba659 100644 (file)
@@ -58,3 +58,18 @@ vector<int> src = {1, 2, 3, 4, 5}, dst;
 partial_sum(src.begin(), src.end(), back_inserter(dst));
 for (unsigned int i = 0; i < dst.size(); i++) cout << dst[i] << " ";
 ```
+
+- 使用 `lower_bound` 查找并输出有序数组 `a` 中最接近 `x` 的元素。
+
+```cpp
+// lower_bound将返回a中第一个大于等于x的元素的地址,计算出的i为其下标
+int i = lower_bound(a, a + n, x) - a;
+// 在以下两种情况下,a[i] (a中第一个大于等于x的元素) 即为答案:
+// 1. a中最小的元素都大于等于x
+// 2. a中存在大于等于x的元素,且第一个大于等于x的元素 (a[i]) 相比于第一个小于x的元素 (a[i - 1]) 更接近x
+// 否则,a[i - 1] (a中第一个小于x的元素) 即为答案
+if (i == 0 || (i < n && a[i] - x < x - a[i - 1]))
+    cout << a[i];
+else
+    cout << a[i - 1];
+```