C++ Multiset Cheatsheet
- Basic Syntax
multiset<int> ms;
- Insertion
ms.insert(10); // Inserts 10
ms.insert(10); // Duplicates allowed
- Iteration
for (int x : ms)
cout << x << " ";
for (auto it = ms.begin(); it != ms.end(); ++it)
cout << *it << " ";
- Deletion
ms.erase(ms.find(10)); // Deletes one occurrence
ms.erase(10); // Deletes ALL occurrences
- Search
auto it = ms.find(10);
if (it != ms.end()) {
cout << "Found";
- Count Duplicates
int c = ms.count(10); // Number of times 10 appears
- Bounds
ms.lower_bound(x); // First element >= x
C++ Multiset Cheatsheet
ms.upper_bound(x); // First element > x
- Size & Emptiness
ms.size(); // Total number of elements
ms.empty(); // Returns true if empty
- Clear All Elements
ms.clear(); // Empties the multiset
- Reverse Iteration
for (auto it = ms.rbegin(); it != ms.rend(); ++it)
cout << *it << " ";
- Initialize with Elements
multiset<int> ms = {5, 1, 3, 3, 7};
- Custom Comparator (Descending Order)
multiset<int, greater<int>> ms;
- Example Use Case: Ticket Problem
multiset<int> prices = {5, 3, 7, 8, 5};
int max_price = 6;
auto it = prices.upper_bound(max_price);
if (it == prices.begin()) cout << -1;
else {
--it;
cout << *it;
prices.erase(it);
C++ Multiset Cheatsheet
- Tips
Prefer multiset when you need:
- Duplicates allowed
- Sorted elements
- Logarithmic insert/delete/search