运行代码后有概率报错 Process finished with exit code -1073741819 (0xC0000005),搜索后得知可能原因之一是空指针异常,使用debug模式查得问题出在lower_bound()函数上。
lower_bound(begin, end, num)从数组的begin位置到end-1位置,二分查找第一个小于或等于num的数字。找到返回该数字的地址,不存在则返回end。因此,需要提防当num恰好等于end的情况。
以我自己的代码为例:
// 判断structure中是否有数字temp
// 若包括则删除数字temp
// vector<int> structure;
// int temp = rand() % key;
vector<int>::iterator comp = lower_bound(structure.begin(), structure.end(), temp);
if (*comp == temp) {
structure.erase(comp);
}

应该修改代码为:
vector<int>::iterator comp = lower_bound(structure.begin(), structure.end(), temp);
if ((*comp == temp) && (comp != structure.end())) {
structure.erase(comp);
}
本文探讨了使用C++标准库函数lower_bound可能导致的空指针异常问题,特别是在删除vector中特定元素时。通过调整条件判断,避免了在末尾位置找不到目标元素时引发的异常。
9万+

被折叠的 条评论
为什么被折叠?



