Std::map::lower_bound正在为大于2000的map键生成核心转储



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

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

#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;
}

你有擦反:

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

只能从较小的迭代器擦除到第一个形参后面的迭代器。在本例中,迭代器指向以下值:

lower: 3000
upper: 2000
and itup < itlow

from lower_bound and upper_bound

lower_bound返回:

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

upper_bound返回:

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

最新更新