📜  使用C ++ STL查找排序后的数组的底面和天花板

📅  最后修改于: 2021-05-31 18:59:40             🧑  作者: Mango

给定一个已排序的数组,任务是使用STL查找给定数字的底数和底数。

例子:

Input: arr[] = {1, 2, 4, 7, 11, 12, 23, 30, 32},
       values[] = { 1, 3, 5, 7, 20, 24 }
Output: Floor Values: 1 2 4 7 12 23 
       Ceil values: 1 4 7 7 23 30 

在floor() :lower_bound()方法的情况下,将使用os STL查找下限。此方法返回大于或等于指定元素的元素的迭代器。

如果是ceil() :upper_bound()方法,将使用os STL查找上限。此方法返回大于或等于指定元素的元素的迭代器。

执行:

// C++ program to find the floor and ceil
// of a given numbers in a sorted array
  
#include 
using namespace std;
  
// Function to find floor of list of
// values using lower_bound in STL
void printFloor(int arr[], int n1,
                int findFloor[], int n2)
{
    // Find and print the Floor Values
    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;
}
  
// Function to find Ceil of list of
// values using upper_bound in STL
void printCeil(int arr[], int n1,
               int findCeil[], int n2)
{
    // Find and print the Ceil Values
    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;
}
  
// Driver code
int main()
{
    // Get the sorted array
    int arr[] = { 1, 2, 4, 7, 11, 12, 23, 30, 32 };
    int n1 = sizeof(arr) / sizeof(arr[0]);
  
    // Print Array
    cout << "Original Array: ";
    for (unsigned int i = 0; i < n1; i++)
        cout << " " << arr[i];
    cout << "\n";
  
    // Given values whose floor and ciel
    // values are needed to find
    int find[] = { 1, 3, 5, 7, 20, 24 };
    int n2 = sizeof(find) / sizeof(find[0]);
  
    // Print Values whose floor
    // and ceil is to be found
    cout << "Values: ";
    for (unsigned int i = 0; i < n2; i++)
        cout << find[i] << " ";
    cout << "\n";
  
    // Print Floor Values
    printFloor(arr, n1, find, n2);
  
    // Print Ceil Values
    printCeil(arr, n1, find, n2);
  
    return 0;
}
输出:
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
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”