【问题标题】:std::map::lower_bound is generating core dump for map key greater than 2000std::map::lower_bound 正在为大于 2000 的映射键生成核心转储
【发布时间】:2016-08-16 06:21:28
【问题描述】:

对于下面的示例程序,lower_bound 正在生成核心转储。知道哪里可能出错了吗?

另外,谁能解释一下lower_bound和upper_bound算法在c++中是如何工作的?

#include <iostream>
#include <map>

int main ()
{
  std::map<int,int> mymap;
  std::map<int,int>::iterator itlow,itup;

  mymap[100]=10;
  mymap[1000]=20;
  mymap[2000]=40;
  mymap[3000]=60;
  mymap[4000]=80;
  mymap[5000]=100;

  itlow=mymap.lower_bound (2001);
  itup=mymap.upper_bound (1500);

  std::cout<<(itlow->first)<<std::endl;
  std::cout<<(itup->first)<<std::endl;
  mymap.erase(itlow,itup);        // erases [itlow,itup)

  // print content:
  for (std::map<int,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  return 0;
}

【问题讨论】:

  • 算法是如何工作的:关于它们的接口,请咨询suitable reference。它们如何在内部工作:地图(很可能)是二叉搜索树,因此找到这样的边界是对这种树的标准遍历。

标签: c++ algorithm stdmap


【解决方案1】:

你有向后擦除:

mymap.erase(itup, itlow);        // erases [itlow,itup)

您只能从较小的迭代器擦除到第一个参数之后的迭代器。在这种情况下,您的迭代器指向值:

lower: 3000
upper: 2000
and itup < itlow

来自lower_bound 和upper_bound

lower_bound 返回:

返回一个指向范围内第一个元素的迭代器 [first,last) 不小于 val。

upper_bound 返回:

返回一个指向范围内第一个元素的迭代器 [first,last) 比较大于 val。

【讨论】:

  • 谢谢。我找到了崩溃的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2023-03-27
  • 2013-07-24
相关资源
最近更新 更多