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

ฟังก์ชัน unordered_multimap::reserve() ใน C++ STL

ฟังก์ชัน unordered_multimap::reserve() ใน C++ STL กำหนดจำนวน Bucket ให้เหมาะสมที่สุดเพื่อรองรับอย่างน้อย n สมาชิก

ถ้า n มากกว่าจำนวน Bucket ปัจจุบันคูณ max_load_factor จะเพิ่ม Bucket และบังคับ Rehash

Reserve() ไม่คืนค่า รับพารามิเตอร์ n ระบุความจูนขั้นต่ำที่ต้องการ

อัลกอริทึม

Begin
    Declare map m
    m.reserve(6) = จองขนาด bucket ให้รองรับอย่างน้อย 1 สมาชิก
    Insert key-value pairs
    Print result
End.

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

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

int main() {
    unordered_map<char, int> m;
    m.reserve(6);
    m.insert(pair<char, int>('b', 10));
    m.insert(pair<char, int>('a', 20));
    cout << "The size is: " << m.size();
    cout << "\nKey and values are: ";
    for (auto it = m.begin(); it != m.end(); it++)
        cout << "{" << it->first << ", " << it->second << "} ";
    return 0;
}

ผลลัพธ์

The size is: 2
Key and values are: {a, 20} {b, 10}