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

order_of_key() ใน C++

คำอธิบาย

order_of_key() เป็นฟังก์ชันของ Policy-Based Data Structure (PBDS) ใน GNU C++ (<ext/pb_ds/assoc_container.hpp>) ใช้กับ tree (ordered_set) คืนจำนวน elements ที่ น้อยกว่า key อย่างเคร่งครัด

ตัวอย่าง

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;

typedef tree<int, null_type, less<int>, rb_tree_tag, 
             tree_order_statistics_node_update> ordered_set;

int main() {
    ordered_set os;
    os.insert(5);
    os.insert(2);
    os.insert(6);
    os.insert(4);
    
    // Elements in order: 2, 4, 5, 6
    cout << "Less than 6: " << os.order_of_key(6) << endl; // 3 (2,4,5)
    cout << "Less than 7: " << os.order_of_key(7) << endl; // 4 (all)
    cout << "Less than 2: " << os.order_of_key(2) << endl; // 0
    cout << "Less than 3: " << os.order_of_key(3) << endl; // 1 (2)
    
    // ฟังก์ชันคู่: find_by_order(k) -> iterator ของ element ลำดับ k (0-indexed)
    cout << "Element at order 2: " << *os.find_by_order(2) << endl; // 5
    
    return 0;
}

เอาต์พุต

Less than 6: 3
Less than 7: 4
Less than 2: 0
Less than 3: 1
Element at order 2: 5