Is ->second defined for iterator std::map::end()?
c++, iterator, stl
Solution
Intuitively I'm assuming it to be valid and fully initialized?
You cannot assume an iterator to an element past-the-end of a container to be dereferenceable. Per paragraph 24.2.1/5 of the C++11 Standard:
Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called past-the-end values. Values of an iterator `i` for which the expression `*i` is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. [...]
Problem
I'm working with a `std::map<std::string, MyClass* >`. I want to test if `my_map.find(key)` returned a specific pointer. Right now I'm doing; ``` auto iter = my_map.find(key); if ((iter != my_map.end()) && (iter->second == expected)) { // Something wonderful has happened } ``` However, the `operator *` of the iterator is required to return a reference. Intuitively I'm assuming it to be valid and fully initialized? If so, `my_map.end()->second` would be `NULL`, and (since `NULL` is never expected), I could reduce my if statement to: ``` if (iter->second == expected) ``` Is this valid according to specification? Does anyone have practical experience with the implementations of this? IMHO, the code becomes clearer, and possibly a tiny performance improvement could be achieved.