【发布时间】:2021-08-26 10:15:38
【问题描述】:
每当我这样做时:
auto itr = ranges::upper_bound(vector, value);
如果value 大于vector 中的任何值,那么它会给我一个错误/崩溃(debug assertion failed)。我想以某种方式避免这种情况。我可能想到的唯一解决方案是:
ranges::sort(vector); // or any code which can find the maximum element in a container
if (*(vector.end()-1) > value)
auto itr = ranges::upper_bound(vector, value);
但是找到最大值意味着更多的工作,我可以用更有效的方式来做吗? 编辑: 我在崩溃时使用的整个代码都在这里:
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
auto main() -> int
{
int n, value;
cin >> n;
vector <int> vector;
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
vector.push_back(a);
}
cin >> value;
ranges::sort(vector);
auto itr = ranges::upper_bound(vector, value);
cout << *itr;
return 0;
}
【问题讨论】:
-
"那么它会给我一个错误/崩溃"我严重怀疑这一点。我怀疑它“崩溃”了,因为您 not 显示的代码正在取消引用该迭代器
itr而无需检查它是否位于范围末端。假设您阅读了 upper_bound 的文档并首先为其提供了一个排序范围。如果不是,您已经在调用 未定义的行为。 -
cout << *itr;==>if (itr != vector.end()) cout << *itr;。 从不取消引用迭代器,除非您知道迭代器引用了 [begin,end) 之间的有效序列元素(注意 begin 是包含的,end 是 exclusive )。阅读文档。upper_bound将在无法限定匹配元素时返回范围结束。
标签: c++ performance containers upperbound