1

I understand the usage on sets in C++, but why do multisets exist? What are some real world applications where multisets are useful?

This argument can extended for unordered multisets as well, what differentiates then from using a vector and what advantages and disadvantages does it provide?

Ayush
  • 91
  • 1
  • 10
  • 3
    Note that multiset can store elements with keys _equal with respect to a given comparator_. This does not necessarily mean that two _equal_ keys have the same contents, whatever it is. – Daniel Langr Jun 15 '20 at 10:57
  • 1
    Relevant: [Give me a practical use-case of Multi-set](https://stackoverflow.com/q/2524480/580083), [“multiset” & “multimap” - What's the point?](https://stackoverflow.com/q/2858127/580083). – Daniel Langr Jun 15 '20 at 11:00
  • 1
    "Equivalent" might be a better word. – Evg Jun 15 '20 at 11:01

1 Answers1

2

Because you don't have to store single-element objects in a multi-set. You're thinking of storing something like a string in a multi-set. But that's not what it's made for. You can have any struct you want, and make the comparison be with a single element in the struct.

For example:

struct PhoneBookEntry
{
    std::string name;
    std::string phoneNumber;
}

In this naive "phone book" entry, there's no reason to have a single entry per name in a phone book. There might be many. So you make a multiset of PhoneBookEntry, and you make the comparator be by name. This way, you can have multiple phone numbers with the same name.

Now you might think that a map is more suitable for this, sure. But this is just an example. If you have a structure where you don't need a key/value but you need the search properties of a set with multiple elements per key, you use a multiset.

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189