vector<int> v = {0,1,3,2};
auto x = upper_bound(v.rbegin(), v.rend(), 1);
cout<<(*x);
This block of code gives output 24576
vector<int> v = {0,1,3,2,2};
auto x = upper_bound(v.rbegin(), v.rend(), 1);
cout<<(*x);
This block gives output 2.
Why?
vector<int> v = {0,1,3,2};
auto x = upper_bound(v.rbegin(), v.rend(), 1);
cout<<(*x);
This block of code gives output 24576
vector<int> v = {0,1,3,2,2};
auto x = upper_bound(v.rbegin(), v.rend(), 1);
cout<<(*x);
This block gives output 2.
Why?
Copyright © 2021 Jogjafile Inc.
std::upper_boundhas a precondition. Quoting cppreference here, not the standard:It is up to you, the caller, to make sure this precondition is satisfied, and your program has undefined behavior if you fail to do so.
Since you pass reverse iterators, the sequence for the algorithm is
2, 3, 1, 0for the first example. (The second has exactly the same issue.) The expression!(1 < element)evaluates for this sequence tofalse, false, true, true, which means thetruevalues don't precede thefalsevalues, i.e. the precondition is violated. Your program has undefined behavior, and the exact resulting values are unpredictable and irrelevant.