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?

bunny
  • 1,797
  • 8
  • 29
  • 58
  • Test 2 has undefined behaviour. – chris Oct 19 '14 at 19:21
  • 1
    Could you please more specific? Thanks! – bunny Oct 19 '14 at 19:22
  • [See here](http://stackoverflow.com/questions/949433/why-are-these-constructs-undefined-behavior) for many such examples. There's also [this](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points?rq=1). – chris Oct 19 '14 at 19:23
  • The code doesnot build `print 1 : 60` is probably a comment. – mpromonet Oct 19 '14 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... – mpromonet Oct 19 '14 at 19:36
  • I would like to know why you say Test2 unreferenced an invalid iterator? – bunny Oct 19 '14 at 20:03
  • You are reading and writing the same variable between sequence points and that's undefined behavior. See this: http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points. – Marius Bancila Oct 19 '14 at 20:15

1 Answers1

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • You can't read from and write to `itlow` "between sequence points". – chris Oct 19 '14 at 19:25
  • @chris: So you're saying it's undefined rather than unspecified? – NPE Oct 19 '14 at 19:27
  • Well, I guess if [SO](http://stackoverflow.com/questions/3690141/multiple-preincrement-operations-on-a-variable-in-cc/3691469#3691469) is to be believed, it is pre-C++11 and not after. It's always fun how things can subtly change. – chris Oct 19 '14 at 19:28