1

I tried to use the lowerbound() in C++ STL Map. Before I use it, I test its functionality through a program like below:

int main () { std::map<int,int> mymap; std::map<int,int>::iterator itlow; mymap[1]=20; mymap[3]=60; mymap[4]=80; mymap[5]=100; itlow=mymap.lower_bound (2); //Test1 std::cout<<(--itlow)->first<<'\n'; //print 1 std::cout<<itlow->second<<'\n'; //print 20 //Test2 std::cout<<(--itlow)->first<<": "<<itlow->second<<'\n'; //print 1 : 60 } 

I tested 1 and 2 separately which means when I tested 1, I commented Test2 and same as reverse. Test 1's result is under my expectation, but I don't understand why Test2 print 60 for the second field instead of 20?

7
  • Test 2 has undefined behaviour. Commented Oct 19, 2014 at 19:21
  • 1
    Could you please more specific? Thanks! Commented Oct 19, 2014 at 19:22
  • See here for many such examples. There's also this. Commented Oct 19, 2014 at 19:23
  • The code doesnot build print 1 : 60 is probably a comment. Commented Oct 19, 2014 at 19:25
  • Moreover Test1 use the first map element and Test2 unreferenced an invalid iterator. You got 1:60 but you can get others values... Commented Oct 19, 2014 at 19:36

1 Answer 1

2

It is unspecified whether (--itlow)->first is evaluated before or after itlow->second. If it's evaluated before, you get 20; otherwise, you get 60.

See order of evaluation of operands.

Sign up to request clarification or add additional context in comments.

3 Comments

You can't read from and write to itlow "between sequence points".
@chris: So you're saying it's undefined rather than unspecified?
Well, I guess if SO is to be believed, it is pre-C++11 and not after. It's always fun how things can subtly change.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.