乐闻世界logo
搜索文章和话题

What 's the difference between std:: multimap < key , value> and std:: map < key , std:: set < value > >

1个答案

1

In the C++ Standard Library, std::multimap and std::map combined with std::set provide distinct approaches for storing associative data, with the primary differences lying in their respective use cases and data organization methods.

std::multimap<key, value>

std::multimap is an associative container that permits duplicate keys. It stores multiple values under the same key, meaning a single key can map to multiple values.

Advantages:

  • Directly supports a one-key-to-multiple-values structure without requiring additional data structures.
  • Inserting new key-value pairs is straightforward, even when keys are duplicated.

Disadvantages:

  • Accessing all values for a specific key may require traversal, as all values are linearly stored under the same key.

Usage Scenario Example: If we need to store multiple teachers for each subject in a school, std::multimap is suitable, where the subject serves as the key and the teacher's name as the value.

cpp
std::multimap<std::string, std::string> subject_teachers; subject_teachers.insert(std::make_pair("Math", "Mr. Smith")); subject_teachers.insert(std::make_pair("Math", "Mrs. Johnson"));

std::map<key, std::set<value>>

std::map is an associative container that does not allow duplicate keys. However, by defining the value as std::set, it indirectly supports multiple non-duplicate values for a single key. In this structure, each key maps to a set that holds all values.

Advantages:

  • Automatically maintains an ordered, non-duplicate set of values for each key.
  • Provides efficient lookup, deletion, and insertion operations, particularly when verifying if a value already exists in the set.

Disadvantages:

  • Compared to std::multimap, insertion requires additional operations, such as checking for value existence.

Usage Scenario Example: If you need to store an independent list of teachers for each subject while ensuring no duplicates, using std::map with std::set is preferable.

cpp
std::map<std::string, std::set<std::string>> subject_teachers; subject_teachers["Math"].insert("Mr. Smith"); subject_teachers["Math"].insert("Mrs. Johnson"); // Attempting to insert "Mrs. Johnson" again has no effect, as the set already contains it.

Summary

Choosing between std::multimap and std::map with std::set depends on specific requirements:

  • If you need to store multiple possibly duplicate values with no uniqueness requirement, std::multimap is appropriate.
  • If values must be unique and you want efficient access to the value collection via the key, using std::map with std::set is the better choice.
2024年6月29日 12:07 回复

你的答案