0

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;
}
KhiemGOM
  • 69
  • 8
  • *"then it will give me an error/crash"* I seriously doubt that. I suspect it is "crashing" because the code you're *not* showing is dereferencing that iterator `itr` without bothering to check if it is sitting on the range end. That, assuming you read the documentation of upper_bound and are feeding it a sorted range in the first place. If you're not, you're already invoking *undefined behavior*. – WhozCraig Aug 26 '21 at 10:19
  • `cout << *itr;` ==> `if (itr != vector.end()) cout << *itr;` . *Never* dereference iterators unless you *know* the iterator is referencing a valid sequence element between [begin,end) (note begin is inclusive, end is *exclusive*). Read the documentation. `upper_bound` will return the range end when no matching element can be qualified. – WhozCraig Aug 26 '21 at 10:24

1 Answers1

3

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.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93