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

Multiset ใน C++ Standard Template Library (STL)

คำอธิบาย

multiset เป็น associative container คล้าย set แต่ อนุญาตให้มีค่าซ้ำได้ จัดเก็บข้อมูลเรียงลำดับอัตโนมัติ (default: น้อยไปมาก)

คุณสมบัติหลัก

  • Insert/Erase/Find: O(log n)
  • รองรับ duplicate values
  • Iterator ชี้ไปตามลำดับที่เรียงแล้ว
  • มี lower_bound, upper_bound, equal_range

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

#include <iostream>
#include <set>
#include <iterator>
using namespace std;

int main() {
    // เรียงมากไปน้อยด้วย greater<int>
    multiset<int, greater<int>> ms1;
    ms1.insert(40);
    ms1.insert(30);
    ms1.insert(60);
    ms1.insert(20);
    ms1.insert(50);
    ms1.insert(50); // duplicate
    ms1.insert(10);
    
    cout << "ms1 (descending): ";
    for(int x : ms1) cout << x << " ";
    cout << endl;
    
    // copy constructor
    multiset<int> ms2(ms1.begin(), ms1.end()); // default ascending
    cout << "ms2 (ascending): ";
    for(int x : ms2) cout << x << " ";
    cout << endl;
    
    // erase elements < 30
    ms2.erase(ms2.begin(), ms2.find(30));
    cout << "After erase < 30: ";
    for(int x : ms2) cout << x << " ";
    cout << endl;
    
    // erase all 50
    int removed = ms2.erase(50);
    cout << "Erased " << removed << " copies of 50" << endl;
    
    // bounds
    cout << "lower_bound(40): " << *ms1.lower_bound(40) << endl;
    cout << "upper_bound(40): " << *ms1.upper_bound(40) << endl;
    
    return 0;
}

เอาต์พุต

ms1 (descending): 60 50 50 40 30 20 10
ms2 (ascending): 10 20 30 40 50 50 60
After erase < 30: 30 40 50 50 60
Erased 2 copies of 50
lower_bound(40): 40
upper_bound(40): 30