Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I found that they have one key and multiple values which is unique.

like image 471
大宝剑 Avatar asked Dec 22 '11 09:12

大宝剑


People also ask

What is difference between map and multimap?

The map and the multimap are both containers that manage key/value pairs as single components. The essential difference between the two is that in a map the keys must be unique, while a multimap permits duplicate keys.

What is STD multimap?

} (2) (since C++17) Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys.

How does multimap determine value by key?

We can find all values of a key in Multimap using is member function equal_range(). It accepts the key as an argument and returns a pair of multimap iterator. This returned pair has a range that represents the entries with given key.

What data structure is used in map and multimap?

A map is a data structure that is primarily used to store key-value pairs. Each key value in a map is mapped to a value. And something to note is that no two values in a map can be mapped to a single index.


1 Answers

A std::map is an associative container, that allows you to have a unique key associated with your type value. For example,

void someFunction() {     typedef std::map<std::string, int> MapType;     MapType myMap;      // insertion     myMap.insert(MapType::value_type("test", 42));     myMap.insert(MapType::value_type("other-test", 0));      // search     auto it = myMap.find("test");     if (it != myMap.end())         std::cout << "value for " << it->first << " is " << it->second << std::endl;     else         std::cout << "value not found" << std::endl; } 

A std::multimap is equal to a std::map, but your keys are not unique anymore. Therefore you can find a range of items instead of just find one unique item. For example,

void someFunction() {     typedef std::multimap<std::string, int> MapType;     MapType myMap;      // insertion     myMap.insert(MapType::value_type("test", 42));     myMap.insert(MapType::value_type("test", 45));     myMap.insert(MapType::value_type("other-test", 0));      // search     std::pair<auto first, auto second> range = myMap.equal_range("test");     for (auto it = range.first; it != range.second; ++it)         std::cout << "value for " << it->first << " can be " << it->second << std::endl; } 

The std::set is like an std::map, but it is not storing a key associated to a value. It stores only the key type, and assures you that it is unique within the set.

You also have the std::multiset, that follows the same pattern.

All these containers provide an O(log(n)) access with their find / equal_range.

like image 191
typedef Avatar answered Sep 19 '22 11:09

typedef