地图中 upper_bound() 的奇怪行为

Strange behavior of upper_bound() in Maps

本文关键字:upper bound 地图      更新时间:2023-10-16

我写了下面的示例代码来理解 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())迭代器是 回来了。

为什么过去结束迭代器返回这样的值?

因为没有键严格大于 30itup 是结束迭代器。不允许取消引用结束迭代器,因此程序具有未定义的行为。

以下行:

std::cout << std::boolalpha << (mymap.upper_bound(30) == mymap.end()) << std::endl; 

确实验证了这是end的迭代器。您不应该取消引用此迭代器。如果你这样做 - 所有的赌注都关闭了,你会得到一些未指定的结果。