0

I am not allow to insert values in multi-map like vectors or arrays using [ ] operator. There is a insert function for insert values in multi-map but how can I insert values using [ ] operator.

Thanks.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    multimap<int,int> mp;

    mp[0] = -1;

    return 0;
}
Evg
  • 25,259
  • 5
  • 41
  • 83
Gaurav_Solo
  • 61
  • 10
  • oh thanks then it means that there is no function to support this operator[] in multimap – Gaurav_Solo Jun 01 '21 at 16:42
  • [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Apr 10 '22 at 21:14

2 Answers2

2

The whole point of multimap is that you can have multiple values at the same key. Keeping that in mind, what is mp[0] supposed to mean?

In std::map<> and std::unordered_map<> it simply means "the value at that key", no sweat. But for std::multimap<> it can't be that simple.

If mp[0] were to return something when using multimap, it would have to be some exotic proxy object that loosely refers to the "list" of items at that particular key, and that would become confusing fast, especially since the other map types just return a simple reference. It's simpler to just not have that operator altogether.

If you want to insert an item in a multimap, use insert() like you've been doing. That also works fine for regular maps by the way, and is actually slightly cleaner if you know you are doing an insertion, as opposed to potentially replacing an already present element at that key.

mp.insert(0, -1);

I'd encourage you to refer to the documentation of map and multimap for specific details of what each of these containers can and cannot do.

0

In multimap, you can have the same key to point different values because there are multiple keys you can't specify which value you need. the key is unique in arrays so u can exactly point to a specific value, The same goes with maps as well as there is no repetition allowed, there are only unique key-value pairs so it makes sense using m[key]=value. so, in multimap, you have the same keys to different values so you cannot use this notation to point to the value.