gcc 为什么std::map::lower_bound对于大小为1的Map失败?

omtl5h9j  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(212)

我可能偶然发现了一个bug,但可能只是他们实现标准库的方式。以下是bug吗?
在gcc 4.8.2和clang 3.4中,如果我在一个只有一个元素的map上使用std::map::lower_bound(),它会返回end(),即使map中的元素是一个下界。
如果您要测试此功能,请务必使用下列编译选项:- 标准品=c++11

#include <cstdlib>
#include <iostream>
#include <map>

#define ts_t std::pair<uint64_t,uint64_t>

int main() {

    std::map<ts_t,uint32_t> test;

    uint32_t count = 0;

    test.insert(std::make_pair(
        std::make_pair(1403187740ull,698599ull),
        count++
    ));

    ts_t key = std::make_pair(1403187740ull,698600ull);

    auto lower = test.lower_bound(key);
    auto upper = test.upper_bound(key);

    if(lower==test.end()) std::cout<<"no lower bound\n";
    if(upper==test.end()) std::cout<<"no upper bound\n";
    if(test.begin()->first < key) std::cout<<"key is less than begin()\n";

    test.insert(std::make_pair(
        std::make_pair(1403187740ull,698601ull),
        count++
    ));

    lower = test.lower_bound(key);
    upper = test.upper_bound(key);

    if(lower==test.end()) std::cout<<"no lower bound\n";
    if(upper==test.end()) std::cout<<"no upper bound\n";
    if(test.begin()->first < key) std::cout<<"key is less than begin()\n";

    return EXIT_SUCCESS;
}

下面是我得到的输出:

no lower bound
no upper bound
key is less than begin()
key is less than begin()

我期望看到:

no upper bound
key is less than begin()
key is less than begin()

**更新:**在回答后,我写了这个更新的代码,它确实完成了我所追求的。我把它贴在这里,以防其他人试图完成同样的事情:

#include <cstdlib>
#include <iostream>
#include <map>

#define ts_t std::pair<uint64_t,uint64_t>

int main() {

    std::map<ts_t,uint32_t> test;

    uint32_t count = 0;

    test.insert(std::make_pair(
        std::make_pair(1403187740ull,698599ull),
        count++
    ));

    ts_t key = std::make_pair(1403187740ull,698600ull);

    std::map<ts_t,uint32_t>::iterator upper = test.upper_bound(key);
    std::map<ts_t,uint32_t>::iterator lower;
    if(upper==test.begin()){
        lower = test.end();
    } else {
        lower = upper;
        --lower;
    }

    if(lower==test.end()) std::cout<<"no lower key\n";
    if(upper==test.end()) std::cout<<"no upper bound\n";
    if(test.begin()->first < key) std::cout<<"key is less than begin()\n";

    test.insert(std::make_pair(
        std::make_pair(1403187740ull,698601ull),
        count++
    ));

    lower = test.lower_bound(key);
    upper = test.upper_bound(key);

    if(lower==test.end()) std::cout<<"no lower key\n";
    if(upper==test.end()) std::cout<<"no upper bound\n";
    if(test.begin()->first < key) std::cout<<"key is less than begin()\n";

    return EXIT_SUCCESS;
}
wmtdaxz3

wmtdaxz31#

你误解了lower_bound的意思。它并不意味着它下面的元素;它意味着不小于即大于或等于的第一个元素。
此函数的目的是使范围lower_boundupper_bound与等于搜索关键字的所有元素匹配。

相关问题