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

Lower Bound ใน C++

คำอธิบาย

std::lower_bound (ใน <algorithm>) หา iterator แรกในช่วงที่เรียงแล้ว ที่มีค่า มากกว่าหรือเท่ากับ ค่าที่กำหนด

  • Complexity: O(log n) สำหรับ random-access iterator
  • ต้องการ container ที่เรียงลำดับแล้ว

ตัวอย่าง

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

int main() {
    vector<int> v = {10, 20, 30, 40, 50};
    
    cout << "Vector: ";
    for(int x : v) cout << x << " ";
    cout << endl;
    
    auto it1 = lower_bound(v.begin(), v.end(), 35);
    cout << "lower_bound(35): index " << (it1 - v.begin()) << ", value " << *it1 << endl;
    
    auto it2 = lower_bound(v.begin(), v.end(), 55);
    cout << "lower_bound(55): index " << (it2 - v.begin()) << " (end) " << endl;
    
    auto it3 = lower_bound(v.begin(), v.end(), 30);
    cout << "lower_bound(30): index " << (it3 - v.begin()) << ", value " << *it3 << endl;
    
    return 0;
}

เอาต์พุต

Vector: 10 20 30 40 50
lower_bound(35): index 3, value 40
lower_bound(55): index 5 (end)
lower_bound(30): index 2, value 30