2

I'd like to use the find() method, to catch a particular element of my std::map()

Now the return value is either the element I was looking for, or it it points to the end of the map if the element hasn't been found (C.f.: http://www.cplusplus.com/reference/map/map/find/ ).

So I'm using these two information whether to decide if an element is in the map or not. But what happens if the element is already inside but at the very end ? My if-query would then decide that it's not existing and therefor my program will be made up.

Am I getting this routine right, and if, how to prevent it ?

Thanks for your support

user3085931
  • 1,757
  • 4
  • 29
  • 55
  • 2
    If you understand "at the very end" as "at `end()`", then there is no element "at the very end". The last element is just before `end()`, because `end()` is _defined_ to be _after_ the last element. By definition, there is no element at `end()`. – Daniel Daranas Jul 18 '14 at 10:52

2 Answers2

9

The last element in any container is not the same as the containers end iterator. The end iterator is actually one step beyond the last element in the container.

That means you can rest easily, and use find without worries. If the element you look for is the last element, you will get what you search for.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks for the help, If it wouldn't be locked I'd mark this as answer. Is this information anywhere else online ? – user3085931 Jul 18 '14 at 10:51
0

You can actually use if(!map.count(elem)) to check whether elem is present in the map, count() returns 0 if elem is not present in the map while find() returns an iterator which has to been compared to the end iterator, i.e., if(map.find(elem) != map.end()).

user1147800
  • 237
  • 4
  • 14
  • 1
    Have you measured the difference in performance between the two? – NonNumeric Jul 18 '14 at 11:15
  • @jarod42, it's cheaper to write indeed, in terms of performance, count may just be a wrapper around find() depends on the implementation, there's another thread talking about the performance of count vs find. http://stackoverflow.com/questions/3886593/how-to-check-if-stdmap-contains-a-key-without-doing-insert – user1147800 Jul 18 '14 at 11:22
  • 1
    Even if they are the same, one could argue that using find() would be preferable because it might be faster on other containers, such as vectors. There, it might pay off to be used to writing `find(x) != map.end()` instead of `count() != 0`. – anderas Jul 18 '14 at 11:26