简体   繁体   中英

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

我发现他们有一个键和多个值是唯一的。

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.

The multimap stores pairs of (key, value) where both key and value can appear several times.

The map<key, set<value>> will only store each value once for a specific key. To do that, it will have to be able to compare the values, not just the keys.

It depends on your application if the values that compare equal are equivalent, or if you wish to store them separately anyway. Perhaps they contain fields that are different but do not take part in the comparison for the set.

map::insert

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value if so, the element is not inserted and its mapped value is not changed in any way.

on the other hand

multimap::insert 

can insert any number of items with the same key.

http://www.cplusplus.com/reference/stl/map/
http://www.cplusplus.com/reference/stl/multimap/

后者要求可以对值进行排序(通过operator<或比较函数),前者不需要。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM