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

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


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

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

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

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

equal_range() เป็นฟังก์ชันในตัวของ C++ STL ที่ประกาศใน header file <set> ฟังก์ชันนี้ส่งคืน ช่วง (range) ของ set container ที่มีค่าเท่ากับอาร์กิวเมนต์ที่ส่งเข้ามา เนื่องจาก set เก็บค่าไม่ซ้ำกัน ช่วงที่พบจะมีเพียงค่าเดียว หากค่าไม่มีใน container ช่วงจะมีขนาด 0 โดย iterator ทั้งคู่จะชี้ไปตำแหน่งแรก

ไวยากรณ์ (Syntax)

Set1.equal_range(const type_t& value);

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

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

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

ส่งคืน pair (หรือ iterator range) เริ่มจาก lower bound จนถึง upper bound ของค่าที่ค้นหา

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

Input: set<int> myset = {10, 20, 30, 40};
myset.equal_range(30);
Output: lower bound of 30 is 30

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

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

int main() {
    set<int> mySet;
    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);
    mySet.insert(40);
    mySet.insert(50);
    
    cout << "Elements before applying range() Function : ";
    for (auto i = mySet.begin(); i != mySet.end(); i++)
        cout << *i << " ";
    
    auto i = mySet.equal_range(30);
    cout << "\nlower bound of 30 is " << *i.first;
    cout << "\nupper bound of 30 is " << *i.second;
    
    i = mySet.equal_range(40);
    cout << "\nlower bound of 40 is " << *i.first;
    cout << "\nupper bound of 40 is " << *i.second;
    
    i = mySet.equal_range(10);
    cout << "\nlower bound of 10 is " << *i.first;
    cout << "\nupper bound of 10 is " << *i.second;
    
    return 0;
}

ผลลัพธ์ (Output)

Elements before applying range() Function : 10 20 30 40 50
lower bound of 30 is 30
upper bound of 30 is 40
lower bound of 40 is 40
upper bound of 40 is 50
lower bound of 10 is 10
upper bound of 10 is 20