Topic 64 of 91 9. C++ Standard Template Library (STL) Interactive Tutorial

std::multiset in C++: Sorted Collections That Allow Duplicates

6 mins read Last updated: 26 Sep 2026 16,768 views

Direct Answer & Core Concept

std::multiset is an associative container that stores sorted elements where duplicate values are permitted. Calling erase(value) removes ALL occurrences of that value; to remove only a single occurrence, you must pass an iterator to erase(iterator).

Detailed Explanation & Mechanics

1. Duplicate Key Storage:

Architecture Diagram
MULTISET ORDERED SEQUENCE:
[ 10 ] ──► [ 20 ] ──► [ 20 ] ──► [ 20 ] ──► [ 30 ] ──► [ 40 ]

2. Erase Behavior Caution:

  • ms.erase(20): Deletes ALL three 20s!
  • ms.erase(ms.find(20)): Deletes ONLY the first 20 found.

Runnable Code Example: std::multiset in C++: Sorted Collections

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <set>

int main() {
    std::multiset<int> scores = {90, 75, 90, 85, 90, 60};

    std::cout << "All Scores (Multiset): ";
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";

    std::cout << "Count of 90s: " << scores.count(90) << "\n";

    // 1. Remove ONLY ONE occurrence of 90
    auto it = scores.find(90);
    if (it != scores.end()) {
        scores.erase(it); // Erase by iterator removes 1 item
    }

    std::cout << "After erasing single 90: ";
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";

    // 2. Remove ALL occurrences of remaining 90s
    scores.erase(90); // Erase by value removes all
    std::cout << "After erasing all 90s: ";
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What is the difference between `multiset::erase(val)` and `multiset::erase(iterator)`?

A: `erase(val)` removes every matching element with that value and returns the count of removed elements. `erase(iterator)` removes only the specific single node referenced by the iterator.
Q

Q: How is `std::multiset` implemented?

A: Like `std::set`, it is typically implemented as a self-balancing Red-Black Tree where equivalent keys are linked together in the tree structure.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

• Be careful when erasing by value: use ms.erase(ms.find(val)) if your intention is to remove only a single instance.
• Use std::multiset for tracking dynamic sliding-window medians and frequency counters.
• Use .equal_range(val) to iterate over all duplicates of a specific value efficiently.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.