tags:

views:

132

answers:

2

Hi, I'm trying to insert multiple times this same key into map but with different values. It doesn't work. I know that operator[] does this job, but my question is, if this behaviour of insert is correct? Shouldn't insert() inserts? I wonder what standard says. Unfortunately I don't have it(Standard for C++) so I can't check.
Thank you for helpful ansers.

+5  A: 

I'm not sure I understand fully, but it sounds like you're overwriting your previous entries in the map; A map only stores one value per key.

Rather, you'd need to use multi_map. This will allow you to insert the same key with different values. You do lose operator[] this way, since it wouldn't really make sense. (When inserting, sure, but that operator also retrieves. Which value should it retrieve?)

Here's an example (modified from here):

#include <iostream>
#include <map>

int main(void)
{
    std::multimap<std::string, int> m;

    m.insert(std::make_pair("a", 1));
    m.insert(std::make_pair("b", 2));
    m.insert(std::make_pair("c", 3));
    m.insert(std::make_pair("a", 4));
    m.insert(std::make_pair("b", 5));
    m.insert(std::make_pair("a", 6));

    std::cout << "Number of elements with key a: " << m.count("a") << endl;
    std::cout << "Number of elements with key b: " << m.count("b") << endl;
    std::cout << "Number of elements with key c: " << m.count("c") << endl;

    std::cout << "Elements in m: " << endl;
    for (m::iterator it = m.begin(); it != m.end(); ++it)
    {
        std::cout << "  [" << it->first << ", " << it->second << "]" << endl;
    }
}
GMan
+4  A: 

If you want to insert the same key with different values, you need std::multimap instead.

The std::map::insert will not do anything if the key already exists. The std::map::operator[] will overwrite the old value.

For STL reference you don`t necesary need the C++ standard itself; something like http://www.cplusplus.com/reference/ will do too.

Laurynas Biveinis
Thanks. And because I have to have at least 15 char I'm typing this text.
There is nothing we can do