How do I insert and erase elements efficiently with std::multiset?

Using std::multiset in C++ allows you to efficiently manage a collection of sorted elements with support for duplicate values. The std::multiset is implemented as a balanced binary search tree, which provides good performance for insertion and erasure.

Inserting Elements

To insert an element into a std::multiset, you can use the insert() method. The insertion operation has an average time complexity of O(log n), which makes it efficient for managing sorted data.

Erasing Elements

To erase an element, you can use the erase() method. The erase() method can remove specific elements, and it also has an average time complexity of O(log n). If you need to remove all occurrences of a particular element, you can utilize the erase(value) overload.

Example

#include #include int main() { std::multiset mySet; // Inserting elements mySet.insert(3); mySet.insert(5); mySet.insert(3); // Duplicate value // Displaying elements std::cout << "Elements in multiset: "; for (int x : mySet) { std::cout << x << " "; } std::cout << std::endl; // Erasing an element mySet.erase(3); // Removes one occurrence of 3 // Displaying elements after erasure std::cout << "Elements after erasing 3: "; for (int x : mySet) { std::cout << x << " "; } std::cout << std::endl; return 0; }

std::multiset C++ insert erase elements collection sorted duplicates efficient