【发布时间】:2014-11-29 04:26:12
【问题描述】:
我可能偶然发现了一个错误,但这可能只是他们实现标准库的方式。以下是错误吗?
在 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;
}
【问题讨论】:
标签: c++11 map gcc standard-library clang