在本教程中,我们将讨论一个程序,该程序使用C ++ STL查找排序数组的底面和顶点。
为了找到排序数组的底面和天花板,我们将分别使用STL中的lower_bound()和upper_bound()函数。
#include <bits/stdc++.h> using namespace std; //查找给定数组的地板 void printFloor(int arr[], int n1, int findFloor[], int n2){ int low; cout << "Floor : "; for (int i = 0; i < n2; i++) { low = (lower_bound(arr, arr + n1, findFloor[i]) - arr); if (arr[low] > findFloor[i]) cout << arr[low - 1] << " "; else cout << arr[low] << " "; } cout << endl; } //查找给定数组的ceil- void printCeil(int arr[], int n1, int findCeil[], int n2){ int up; cout << "Ceil : "; for (int i = 0; i < n2; i++) { up = (upper_bound(arr, arr + n1, findCeil[i]) - arr); if (arr[up] > findCeil[i] && arr[up - 1] == findCeil[i]) { cout << arr[up - 1] << " "; } else cout << arr[up] << " "; } cout << endl; } int main(){ int arr[] = { 1, 2, 4, 7, 11, 12, 23, 30, 32 }; int n1 = sizeof(arr) / sizeof(arr[0]); cout << "Original Array: "; for (unsigned int i = 0; i < n1; i++) cout << " " << arr[i]; cout << "\n"; int find[] = { 1, 3, 5, 7, 20, 24 }; int n2 = sizeof(find) / sizeof(find[0]); cout << "Values: "; for (unsigned int i = 0; i < n2; i++) cout << find[i] << " "; cout << "\n"; printFloor(arr, n1, find, n2); printCeil(arr, n1, find, n2); return 0; }
输出结果
Original Array: 1 2 4 7 11 12 23 30 32 Values: 1 3 5 7 20 24 Floor : 1 2 4 7 12 23 Ceil : 1 4 7 7 23 30