Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map::iterator decrement on single element [duplicate]

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

like image 261
queen3 Avatar asked Feb 09 '26 20:02

queen3


2 Answers

Decrementing something to the element before begin() doesn't make sense. This is undefined behavior and there is no correct or incorrect answer.

like image 161
olevegard Avatar answered Feb 15 '26 15:02

olevegard


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.

like image 22
msam Avatar answered Feb 15 '26 16:02

msam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!