Junior — Middle
Can you give an example of a situation where using a multiset data structure is justified?
sobes.tech AI
Answer from AI
Multiset (multiset) is a data structure that stores elements considering the number of their occurrences, allowing repetitions.
An example situation where a multiset is justified:
Imagine a voting system where it is necessary to count how many times each candidate received votes. It is important not just to know who voted, but how many votes each candidate received.
In C++, you can use std::multiset to store votes:
#include <iostream>
#include <set>
int main() {
std::multiset<std::string> votes;
votes.insert("Alice");
votes.insert("Bob");
votes.insert("Alice");
std::cout << "Votes for Alice: " << votes.count("Alice") << std::endl; // 2
std::cout << "Votes for Bob: " << votes.count("Bob") << std::endl; // 1
}
Thus, a multiset is useful when not only the uniqueness of elements matters, but also their quantity.