std::map::lower_bound 正在为大于 2000 的映射键生成核心转储
std::map::lower_bound is generating core dump for map key greater than 2000
对于下面的示例程序,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;
}
你有反向擦除:
mymap.erase(itup, itlow); // erases [itlow,itup)
您只能从较小的迭代器擦除到第一个参数之后的迭代器。在这种情况下,您的迭代器指向值:
lower: 3000
upper: 2000
and itup < itlow
来自 lower_bound and upper_bound
lower_bound
returns:
Returns an iterator pointing to the first element in the range
[first,last) which does not compare less than val.
upper_bound
returns:
Returns an iterator pointing to the first element in the range
[first,last) which compares greater than val.
对于下面的示例程序,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;
}
你有反向擦除:
mymap.erase(itup, itlow); // erases [itlow,itup)
您只能从较小的迭代器擦除到第一个参数之后的迭代器。在这种情况下,您的迭代器指向值:
lower: 3000
upper: 2000
and itup < itlow
来自 lower_bound and upper_bound
lower_bound
returns:
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
upper_bound
returns:
Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.