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

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


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

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

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

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

map::value_comp() คืนค่า Comparison Object (Function Object) ที่ Map ใช้เปรียบเทียบ Value โดย Default เป็น Less-than Operator (operator<) คืนค่า true ถ้า Element แรกน้อยกว่า Element ที่สอง

Syntax

map_name.value_comp();

Parameters

ไม่มีพารามิเตอร์

Return Value

Comparison Object ของ Map Container

ตัวอย่าง

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<char, int> TP = {
        {'a', 10},
        {'b', 20},
        {'c', 30},
        {'d', 40},
        {'e', 50}
    };
    
    auto temp = *TP.rbegin(); // Element สุดท้าย (Key ใหญ่สุด)
    auto it = TP.begin();
    
    cout << "Elements in map are : \n";
    do {
        cout << it->first << " = " << it->second << endl;
    } while (TP.value_comp()(*it++, temp));
    
    return 0;
}

ผลลัพธ์

Elements in map are :
a = 10
b = 20
c = 30
d = 40
e = 50

คำอธิบาย

โค้ดใช้ value_comp() เพื่อ Iterate ทั้ง Map โดยเปรียบเทียบ Element ปัจจุบันกับ Element สุดท้าย จนกว่าจะถึง Element สุดท้าย

หมายเหตุ: ใช้ key_comp() สำหรับเปรียบเทียบ Key (พบบ่อยกว่า)