Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ->second defined for iterator my_map.end()?

Tags:

c++

iterator

stl

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.

like image 685
Rawler Avatar asked Apr 28 '13 20:04

Rawler


People also ask

What does iterator -> Second mean?

Refers to the first ( const ) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression: i->second.

What does the end iterator point to?

In something like an std::vector the ::end() iterator will point to one past the last element. You can't dereference this iterator but you can compare it to another iterator. If you compare another iterator to end() you know you've reached the end of the container.

What is map end () in C++?

C++ Map Library - end() Function The C++ function std::map::end() returns an iterator which points to past-the-end element in the map. The past-the-end element is the theoretical element that would follow the last element in the map.

How do you show first and second of map?

begin()->first to get the key and myMap. begin()->second to get the value. myMap. begin() returns an iterator.


1 Answers

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. [...]

like image 130
Andy Prowl Avatar answered Oct 11 '22 02:10

Andy Prowl