0

arr[]= {1,3,3,7,4,4} upper_bound(arr+3,arr+6,3,greater<int>())-arr should return 5 right (It should point to last 4 whose index is 5 because it is the first greater element after 3 ) ? But it is returning 6.What am I missing here?

yadav_gaurav
  • 15
  • 1
  • 6
  • 1
    @NathanOliver The range is `arr+3,arr+6`. It is `7, 4, 4` and this is sorted. – MikeCAT Mar 15 '21 at 13:42
  • check the parameters of upper_bound(), I am passing [arr+3 ,arr+6) – yadav_gaurav Mar 15 '21 at 13:43
  • @MikeCAT Dang off by one errors ;) – NathanOliver Mar 15 '21 at 13:43
  • 1
    "greater" has its meaning flipped since it really means "opposite direction of the predicate", and is not the default of `less` – JDługosz Mar 15 '21 at 13:44
  • @MikeCAT sorted non-decreasing order... – bean Mar 15 '21 at 13:44
  • Look at the "Second implementation" source code at: https://en.cppreference.com/w/cpp/algorithm/upper_bound . If necessary, paste that into your file and call it instead, and you can follow it in the debugger. – JDługosz Mar 15 '21 at 13:48
  • 1
    TL;DR of the dupe: the opposite of `<` is `>=`, not `>`. You need `std::greater_equal` – NathanOliver Mar 15 '21 at 13:49
  • 1
    No, it doesn't mean `[arr+6,arr+3)` like a reverse iterator. I was thinking that "greater" in your quote is actually (!comp(left,right)) which is the opposite of `comp` which is `greater<>`. It ran to the End before finding a match. – JDługosz Mar 15 '21 at 13:50
  • @JDługosz I don't understand :( – yadav_gaurav Mar 15 '21 at 13:51
  • Your `upper_bound` currently returns `std::end(arr)` (or rather `arr + 6`) which means it didn't find a matching element. – Ted Lyngmo Mar 15 '21 at 13:52
  • @TedLyngmo but the first number that is greater than 3 is 4 whose index is 5 . – yadav_gaurav Mar 15 '21 at 13:53
  • There is no number *less than* 3 in that sequence. that `upper_bound` looks for the first `elem` where `comp(elem, 3)` is false, and none are – Caleth Mar 15 '21 at 14:09
  • If you still don't understand, trace through the simple implementation I noted earlier. Also, if "greater" is still messing you up, remove the predicate argument and negate all the test values and look at it again. – JDługosz Mar 15 '21 at 14:54

0 Answers0