Map.find(x) vs map[x]

Hello guys,

Today I was solving FENCE ( INOI 2017 ) problem: https://www.codechef.com/INOIPRAC/problems/TINOI17A

( SPOILERS AHEAD ) :

**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**

I solved it using maps and in my first code I used map[x] and I got WA ( why ?? ) and TLE ( why ?? )
Here is my first ( WA and TLE ) code :

https://www.codechef.com/viewsolution/28425053

And then I used map.find(x) instead of map[x] and I got AC ( wutt ?? ) and here is my AC code: https://www.codechef.com/viewsolution/28425145

I am a bit surprised :frowning: by this
I wanted to know why the first code gave me TLE and WA while the second code gave me AC

Thanks a lot !!
:slight_smile:

I am 90% sure that it’s because using map[x] actually creates an instance of x in map and adds it to the list to be iterated.On the other hand map.find() doesn’t create any such instance and just checks the presence of the element in the map.So map size remains the same if we use find function.

6 Likes

Oh ok
Thanks a lot !! :slight_smile: @pro_noobie

1 Like

I thought of using unordered_map instead of a map and it is showing some error which I am not able to understand
Which STL function available in maps is not available in unordered_map?

Thanks :slight_smile:

You have to define a custom hash function, if you want to use non standard data types in unordered_map. The Hash function for int is predefined, but not for stl. For a map, a hash function is not needed but only a < operator should be defined, which it is for stl. You may check this link to learn more about it.

2 Likes

You can also use map.count() i think :slightly_smiling_face:

1 Like

In C++20, we’ll finally be ascending from barbarism and adding a std::map::contains method!!!

6 Likes