What should std::map iterator decrement return, if there's only single element in the map? Here's the sample code
#include <map>
#include <stdio.h>
int main()
{
std::map<int, int> m;
m.insert(std::make_pair(1, 1));
//std::map<int, int>::iterator it = m.begin();
std::map<int, int>::iterator it = m.upper_bound(0);
printf("isbegin: %d\n", it == m.begin());
--it;
bool isend = it == m.end();
printf("isend: %d\n", isend);
}
On Windows it will print isend: 1, on Linux with g++ 4.6 it will print isend: 0.
The question: is the decrement above really a case of UB? and if not then what result is correct - Windows or Linux one?
UPDATE: modified code to show that upper_bound is called
Decrementing something to the element before begin() doesn't make sense. This is undefined behavior and there is no correct or incorrect answer.
for an iterator r the operation --r is valid if before the operation is done there exists s such that r == ++s and after the operation is done r is dereferenceable. (§24.2.6 Bidirectional.iterators )
Since begin() returns an iterator to the first element of the container there is no element s which can be incremented to get to r so this is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With