V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cfans1993
V2EX  ›  程序员

C++ STL set 容器中插入相同的值时,对 upper_bound 是否有影响

  •  
  •   cfans1993 · 2015-01-25 20:58:30 +08:00 · 8890 次点击
    这是一个创建于 3378 天前的主题,其中的信息可能已经有所发展或是发生改变。

    上关键代码:
    set<int> c;
    c.insert(1);
    c.insert(2);
    c.insert(3);
    c.insert(4);
    c.insert(5);

    cout<<c.size()<<endl;
    copy(c.begin(),c.end(),ostream_iterator<int>(cout," "));
    cout<<endl;
    cout<<"lower_bound(3) "<<*c.lower_bound(3)<<endl;
    cout<<"upper_bound(3) "<<*c.upper_bound(3)<<endl;
    cout<<"equal_range(3) "<<*c.equal_range(3).first<<" "
    <<*c.equal_range(3).second<<endl;

    代码大致意图:
    新建set容器,插入1,2,3,4,5,然后求得各种bound
    打印结果是:
    5
    1 2 3 4 5
    lower_bound(3) 3
    upper_bound(3) 4
    equal_range(3) 3 4
    Press any key to continue

    修改的分割线————————————————————————————————

    当我把前面c.insert(4)改成c.insert(3)后,
    结果是这样的:
    4
    1 2 3 5
    lower_bound(3) 3
    upper_bound(3) 5
    equal_range(3) 3 5
    Press any key to continue

    问题的分割线————————————————————————————————
    set容器不能重复元素,可为什么修改后,upper_bound(3)会由4变成5?

    8 条回复    2015-01-27 07:57:13 +08:00
    1423
        1
    1423  
       2015-01-25 21:42:23 +08:00
    没人回复,好吧,我来
    不是 5,那你认为应该是几?
    messyidea
        2
    messyidea  
       2015-01-25 22:50:24 +08:00
    4都没有,当然是5了。。我不知道lz想要表达什么。。
    Dannytmp
        3
    Dannytmp  
       2015-01-25 22:53:03 +08:00
    C++太TM复杂了,早早放弃鸟
    spacewander
        4
    spacewander  
       2015-01-25 23:22:56 +08:00
    ……因为你第二次没有插入4,比3更大的数字就是5了。
    66450146
        5
    66450146  
       2015-01-25 23:24:54 +08:00
    本来就不应该直接用 *c.upper_bound(3) 这样的写法,因为 upper_bound 有可能是 .end()

    多看文档吧
    inevermore
        6
    inevermore  
       2015-01-26 09:37:51 +08:00
    楼上说的对,起码先判断一下是不是end
    ryd994
        7
    ryd994  
       2015-01-27 02:06:04 +08:00
    拜托,你都*了,出来的是内容又不是下标……再说了set也没下标一说啊(key=value)
    cfans1993
        8
    cfans1993  
    OP
       2015-01-27 07:57:13 +08:00
    @ryd994 第一天晚上硬是看不明白,然后第二天早上起来一下就看明白了,都不敢看回复了,简直so no face
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3185 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 10:49 · PVG 18:49 · LAX 03:49 · JFK 06:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.