2014-10-19 64 views
1

我试过在C++ STL Map中使用lowerbound()。在我使用它,我通过程序像下面测试其功能:C++ map lowerbound()

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   
} 

我单独测试1和2,当我测试1,这意味着,我评论的Test2和相同的反向。 测试1的结果符合我的预期,但我不明白为什么Test2会打印第二个字段而不是20个字段?

+0

测试2有未定义的行为。 – chris 2014-10-19 19:21:22

+1

请问你能具体吗?谢谢! – diane 2014-10-19 19:22:57

+0

[见这里](http://stackoverflow.com/questions/949433/why-are-these-constructs-undefined-behavior)许多这样的例子。还有[this](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points?rq=1)。 – chris 2014-10-19 19:23:52

回答

2

未指定(--itlow)->first是在itlow->second之前还是之后评估的。如果之前评估过,则获得20;否则,你得到60

参见order of evaluation of operands

+0

您无法读取和写入序列点之间的'itlow'“。 – chris 2014-10-19 19:25:27

+0

@chris:你说这是未定义的而不是未指定的? – NPE 2014-10-19 19:27:12

+0

好吧,我想如果[SO](http://stackoverflow.com/questions/3690141/multiple-preincrement-operations-on-a-variable-in-cc/3691469#3691469)是相信的,它是预先-C++ 11而不是之后。事物如何巧妙地改变总是很有趣。 – chris 2014-10-19 19:28:00