Maps with repeat Keys

So quick question about maps with repeated keys. Say you have a map with the template set as such map<string, set<int>> If a key is used more than once but with different values does it place all those values in the set or create another "unique" index with a different value?

If you have :
1
2
3
map<int, int> myMap;
myMap[0] = 1;
myMap[0] = 2;
The line 3 replaces the value for key 0.

If you're mapping to a set, then you have to add the values to the set:

1
2
3
map<int, set<int>> myMap;
myMap[0].insert(1);
myMap[0].insert(2);


You might also look at multimap, which lets you have duplicate values for a single key.
http://www.cplusplus.com/reference/map/multimap/
In both std::map and std::set, the keys are unique.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <string>
#include <set>
#include <map>

bool add_value( std::map< std::string, std::set<int> >& map,
                const std::string& key, int value )
{
    return map[key].insert(value).second ;
}

int main()
{
    std::map< std::string, std::set<int> > map ;

    const auto try_add = [&] ( const std::string& key, int value )
    {
        std::cout << "key '" << key << "'  value " << value << " : " ;
        if( add_value( map, key, value ) ) std::cout << "inserted value\n" ;
        else std::cout << "value is already present for this key\n" ;
    };

    try_add( "abcd", 7 ) ; // key 'abcd'  value 7 : inserted value
    try_add( "abcd", 8 ) ; // key 'abcd'  value 8 : inserted value
    try_add( "efgh", 7 ) ; // key 'efgh'  value 7 : inserted value
    try_add( "abcd", 7 ) ; // key 'abcd'  value 7 : value is already present for this key
    try_add( "abcd", 9 ) ; // key 'abcd'  value 9 : inserted value
    try_add( "efgh", 3 ) ; // key 'efgh'  value 3 : inserted value

    std::cout << "\nthe map contains:\n--------------\n" ;
    for( const auto& [key,set] : map )
    {
        std::cout << "key '" << key << "'  values: [" ;
        for( int value : set ) std::cout << value << ' ' ;
        std::cout << "]\n" ;
    }
    /*
    the map contains:
    --------------
    key 'abcd'  values: [7 8 9 ]
    key 'efgh'  values: [3 7 ]
    */
}

http://coliru.stacked-crooked.com/a/cdfa3337710d01ea
Thanks everyone! This really helps with my understanding of maps and map/set
Topic archived. No new replies allowed.