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

set::upper_bound() ใน C++ STL


ในบทความนี้เราจะอธิบาย set::upper_bound() ใน C++ STL รวมถึงไวยากรณ์ การทำงาน และค่าที่ส่งคืน

Set ใน C++ STL คืออะไร?

Set ใน C++ STL เป็นคอนเทนเนอร์ที่เก็บ องค์ประกอบที่ไม่ซ้ำกัน (unique) ในลำดับที่จัดเรียงแล้ว ค่าขององค์ประกอบระบุตัวตนของมันเอง เมื่อเพิ่มค่าใน set แล้วไม่สามารถแก้ไขได้ แต่ยังสามารถลบหรือเพิ่มค่าใหม่ได้ Set ถูกนำไปใช้งานเป็น binary search tree

set::upper_bound() คืออะไร?

upper_bound() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน iterator ไปยัง upper bound ของค่าที่ต้องการค้นหา นั่นคือ iterator ที่ชี้ไปยัง องค์ประกอบถัดไปทันที (immediate next element) ที่มากกว่าค่าที่ค้นหา

ไวยากรณ์ (Syntax)

name_of_set.upper_bound(const type_t& value);

พารามิเตอร์ (Parameters)

รับพารามิเตอร์หนึ่งคือค่าที่ต้องการหา upper bound

ค่าที่ส่งคืน (Return Value)

ส่งคืน iterator ชี้ไปยังองค์ประกอบถัดไปที่มากกว่าค่าที่ค้นหา

ตัวอย่างการใช้งาน

Input: set<int> myset = {1, 2, 3, 4, 5};
myset.upper_bound(3);
Output: Upper bound = 4

ตัวอย่างโค้ดเต็ม 1

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

int main() {
    set<int> Set;
    Set.insert(9);
    Set.insert(7);
    Set.insert(5);
    Set.insert(3);
    Set.insert(1);
    
    cout << "Elements are : ";
    for (auto i = Set.begin(); i != Set.end(); i++)
        cout << *i << " ";
    
    auto i = Set.upper_bound(5);
    cout << "\nupper bound of 5 in the set is: " << (*i) << endl;
    
    i = Set.upper_bound(1);
    cout << "upper bound of 1 in the set is: " << (*i) << endl;
    
    return 0;
}

ผลลัพธ์ (Output)

upper bound of 5 in the set is: 7
upper bound of 1 in the set is: 3

ตัวอย่างโค้ดเต็ม 2 (ใช้กับ erase)

#include <iostream>
#include <set>

int main() {
    std::set<int> Set;
    std::set<int>::iterator one, end;
    
    for (int i = 1; i < 10; i++)
        Set.insert(i * 10);
    
    one = Set.lower_bound(20);
    end = Set.upper_bound(40);
    Set.erase(one, end); // ลบช่วง [20, 40)
    
    std::cout << "Elements are: ";
    for (std::set<int>::iterator i = Set.begin(); i != Set.end(); ++i)
        std::cout << ' ' << *i;
    std::cout << '\n';
    return 0;
}

ผลลัพธ์ (Output)

Elements are : 10 50 60 70 80 90