Search code examples
c++performancecontainersupperbound

Avoid crash from std::upper_bound


Whenever I do this:

auto itr = ranges::upper_bound(vector, value);

If the value is greater than any value in the vector, then it will give me an error/crash (debug assertion failed). I want to avoid this somehow. The only solution I might think of is this:

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);

But finding the maximum means more work, can I do it in a more efficient way? Edit: The whole code I use when crashing is here :

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

Solution

  • From cppreference:

    Returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found.

    This means that it may return the end iterator. In that case, you are not allowed to dereference it.