[go: up one dir, main page]

0% found this document useful (0 votes)
30 views3 pages

CPP Multiset Cheatsheet

This C++ Multiset Cheatsheet provides essential operations for using multiset, including insertion, deletion, iteration, and searching for elements. It highlights features such as counting duplicates, bounds, size, and custom comparators. The document also includes example use cases and tips for when to prefer multiset for managing sorted elements with duplicates.

Uploaded by

Yash Mathuria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views3 pages

CPP Multiset Cheatsheet

This C++ Multiset Cheatsheet provides essential operations for using multiset, including insertion, deletion, iteration, and searching for elements. It highlights features such as counting duplicates, bounds, size, and custom comparators. The document also includes example use cases and tips for when to prefer multiset for managing sorted elements with duplicates.

Uploaded by

Yash Mathuria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

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

You might also like