-3

In the case of unordered_map in C++, what is the main difference between:

  1. if(map.find(n) != map.end())
  2. if(map.count(n) > 0)
  3. if(map[n] > 0)

Consider map is an unordered_map of type <int,int>.

  • 1
    3) will create a new entry if not already. Read the documentation [std::unordered_map](https://en.cppreference.com/w/cpp/container/unordered_map) or a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Oct 23 '22 at 06:52
  • 3
    This looks more like a homework question and you've made no effort to read the documentation. – Jason Oct 23 '22 at 06:54
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 23 '22 at 11:16
  • [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822) – kotatsuyaki Oct 23 '22 at 11:16

1 Answers1

1

These lines:

if(map.find(n) != map.end())

if(map.count(n) > 0)

Are mostly equivalent. map::count will never return more than 1.

This line:

if(map[n] > 0)

Loads the value associated with the key, n and compares if it's value is greater than zero. Not the same thing as the first two. map[n] also has a side effect. If n is not already a key in the map, the map will create a new value ("default initialized" or "zero-init" value) for that key. Hence, it can increase the size of the map implicitly.

selbie
  • 100,020
  • 15
  • 103
  • 173