-2

If some key is already present in the map then what will happen

If some key is already present in the map and we are trying the insert different value with same key then what will happen

  • I would expect that the new value you provided would overwrite the old value in the map that was previously associated with that key. – Jeremy Friesner Mar 13 '23 at 07:01
  • 2
    Please show a [mre], what happens depends on the code you use – Alan Birtles Mar 13 '23 at 07:08
  • if multiple instances with the same key are needed in the map, then you can use std::multimap and iterate over the keys from std::multimap::lower_bound to std::multimap::upper_bound. I'm not sure if this answers the question. – stefaanv Mar 13 '23 at 09:23
  • 1
    This is trivial to look up. See [std::map::insert](https://en.cppreference.com/w/cpp/container/map/insert) and [std::map::operator\[\]](https://en.cppreference.com/w/cpp/container/map/operator_at) – Jesper Juhl Mar 13 '23 at 10:44

3 Answers3

2

If you use insert, emplace, emplace_hint or try_emplace, nothing is changed in the map.

If you assign through [] or use insert_or_assign, the value you supply replaces the existing value.

Caleth
  • 52,200
  • 2
  • 44
  • 75
0

In a c++ std::map the previous existing value is overwritten. This is the desired standard behavior of a map.

The same is true for similar map-constructs in any programming language, e.g. "dict" in python etc.

Ralf Ulrich
  • 1,575
  • 9
  • 25
-1

The value that is already in the map will simply get overwritten if you simply assign using [] or insert_or_assign

I've put below an example of what you can expect

int main()
{
    map<string, int> mp = { {"Hello", 1} };
    std::cout << mp["Hello"];
    //outputs 1
    mp["Hello"] = 15;
    std::cout << mp["Hello"];
    //outputs 15
}

but if you are using insert, emplace, emplace_hint or try_emplace and the value is already inside the map, then nothing will happen to the map.

edy131109
  • 1
  • 4