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

时间:2014-10-03 20:08:29

标签: c++11 map gcc standard-library clang

我可能偶然发现了一个错误,但它可能只是他们实现标准库的方式。以下是错误吗?

在gcc 4.8.2和clang 3.4中,如果我在只有一个元素的地图上使用std :: map :: lower_bound(),即使地图中的元素是下限,它也会返回end() 。请参阅以下示例代码。

如果要测试它,请确保使用以下编译选项:-std = 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;
}

1 个答案:

答案 0 :(得分:2)

你误解了lower_bound的含义。它并不意味着它下面的元素;它意味着第一个不小于,即大于或等于的元素。

此功能的目的是使范围lower_boundupper_bound匹配与搜索关键字相同的所有元素。