地图中 upper_bound() 的奇怪行为
Strange behavior of upper_bound() in Maps
我写了下面的示例代码来理解 Map 中的 upper_bound(),但我无法理解以下行为:-
// Sample upper_bound()
#include <iostream>
#include <map>
#include <limits>
int main ()
{
std::map<unsigned int,int> mymap;
std::map<unsigned int,int>::iterator itup;
mymap[0] = 5;
mymap[5] = 5;
mymap[10] = 5;
mymap[15] = 5;
mymap[20] = 5;
mymap[25] = 5;
mymap[30] = 5;
// print content:
for (std::map<unsigned int,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << 'n';
itup=mymap.upper_bound (30);
std::cout<<"First "<< itup->first<<": Second "<< itup->second<<"n";
return 0;
}
从 http://en.cppreference.com/w/cpp/container/map/upper_bound,
"迭代器指向大于键的第一个元素。如果 没有找到这样的元素,过去的结束(参见 end())迭代器是 回来了。
为什么过去结束迭代器返回这样的值?
因为没有键严格大于 30
,itup
是结束迭代器。不允许取消引用结束迭代器,因此程序具有未定义的行为。
以下行:
std::cout << std::boolalpha << (mymap.upper_bound(30) == mymap.end()) << std::endl;
确实验证了这是end
的迭代器。您不应该取消引用此迭代器。如果你这样做 - 所有的赌注都关闭了,你会得到一些未指定的结果。
相关文章:
- 空集"Out of bound iterator"
- 使用多个文件时"array bound is not an integer constant before ']' token"
- "A reference may be bound only to an object",为什么"const int &ref = 3;"有效?
- 如何修复"reference cannot be bound to dereferenced null pointer"警告
- GCC 检测"subindex out of bound"错误
- 如果我没有得到分段错误,如何找到"index out of bound"
- 一个程序将字符串Upper char更改为Lower char得到错误
- 在main中声明Array之前,Array bound不是整型常量
- 获取错误"array bound is not an integer constant before ']' token"
- 在运行时创建结构时"array bound is not an integer constant"
- 错误:无法将参数"1"的"char*"转换为"char**"到"int upper(char**)"