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

ฟังก์ชัน set::lower_bound() ใน C++ STL

ฟังก์ชัน set::lower_bound() ใน C++ STL คืนค่า Iterator ชี้ไปที่สมาชิกใน Container ที่เทียบเท่ากับ Key ที่ส่งผ่านพารามิเตอร์ หาก Key ไม่อยู่ใน Set จะคืน Iterator ชี้ไปยังสมาชิกถัดไปที่มากกว่า Key ทันที

อัลกอริทึม

Begin
    Initialize empty set container s
    Initialize set container as iterator
    Insert elements into s
    Call function to find lower bound of given key passed to iterator
    Print lower bound value
End.

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

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

int main() {
    set<int> s; set<int>::iterator iter;
    s.insert(7); s.insert(6); s.insert(1); s.insert(4);
    s.insert(2); s.insert(9); s.insert(10);
    iter = s.lower_bound(4); cout << "The lower bound of 4 is: " << *iter << endl;
    iter = s.lower_bound(5); cout << "The lower bound of 5 is: " << *iter << endl;
    iter = s.lower_bound(30); cout << "The lower bound of 30 is: " << *iter << endl;
    return 0;
}

ผลลัพธ์

The lower bound of 4 is: 4
The lower bound of 5 is: 6
The lower bound of 30 is: 7