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

ฟังก์ชัน map::upper_bound() ใน C++ STL


ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::upper_bound() ใน C++ STL

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

Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน

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

map::upper_bound(k) คืน Iterator ชี้ไปที่ Element แรกที่มี Key มากกว่า k อย่างเคร่งครัด (Strictly Greater) ไม่รวม Key เท่ากับ k

Syntax

map_name.upper_bound(key& k);

Parameters

k − Key ที่ต้องการค้นหา Upper Bound

Return Value

Iterator ชี้ Element ที่ Key > k แรกที่พบ ถ้าไม่มี คืน end()

ตัวอย่าง

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

int main() {
    map<int, int> TP_Map;
    TP_Map.insert({5, 50});
    TP_Map.insert({2, 30});
    TP_Map.insert({1, 10});
    TP_Map.insert({4, 70});
    
    cout << "TP Map is : \nMAP_KEY\tMAP_ELEMENT\n";
    for (auto i = TP_Map.rbegin(); i != TP_Map.rend(); i++)
        cout << i->first << "\t" << i->second << endl;
    
    auto it = TP_Map.upper_bound(2);
    cout << "The upper bound of key 2 is " << it->first << " : " << it->second << endl;
    
    auto it2 = TP_Map.upper_bound(3);
    cout << "The upper bound of key 3 is " << it2->first << " : " << it2->second << endl;
    
    return 0;
}

ผลลัพธ์

TP Map is:
MAP_KEY     MAP_ELEMENT
5           50
4           70
2           30
1           10
The upper bound of key 2 is 4 : 70
The upper bound of key 3 is 4 : 70

คำอธิบาย

  • Key 2: Upper bound คือ Key 4 (Key ถัดไปที่ > 2)
  • Key 3: ไม่มีใน Map แต่ Upper bound ยังคงเป็น Key 4 (Key ถัดไปที่ > 3)

ความแตกต่างกับ lower_bound()

  • lower_bound(k) = Key แรกที่ ≥ k (รวม k)
  • upper_bound(k) = Key แรกที่ > k (ไม่รวม k)