Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why insert from std::map doesn't want to update? [C++]

Tags:

c++

map

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.

like image 312
There is nothing we can do Avatar asked Jan 08 '10 11:01

There is nothing we can do


2 Answers

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.

like image 131
Laurynas Biveinis Avatar answered Oct 21 '22 11:10

Laurynas Biveinis


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;
    }
}
like image 5
GManNickG Avatar answered Oct 21 '22 09:10

GManNickG