Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การหา Floor และ Ceil ของอาร์เรย์ที่จัดเรียงแล้วด้วย C++ STL

ในบทช่วยสอนนี้ เราจะพูดถึงวิธีหา floor และ ceil ของอาร์เรย์ที่จัดเรียงแล้วโดยใช้ C++ STL

เพื่อหา floor และ ceil เราจะใช้ฟังก์ชัน lower_bound() และ upper_bound() จาก STL ตามลำดับ

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

// หา floor ของอาร์เรย์ที่กำหนด
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

คำอธิบาย

  • Floor: ค่าที่มากที่สุดในอาร์เรย์ที่น้อยกว่าหรือเท่ากับค่าที่ค้นหา
  • Ceil: ค่าที่น้อยที่สุดในอาร์เรย์ที่มากกว่าหรือเท่ากับค่าที่ค้นหา
  • lower_bound คืน iterator ชี้ไปยังองค์ประกอบแรกที่ ≥ ค่าที่ค้นหา
  • upper_bound คืน iterator ชี้ไปยังองค์ประกอบแรกที่ > ค่าที่ค้นหา