text: Upper bound returns pointer to position of next higher number than a [ i ] + mid in a [ i . . n - 1 ] . We subtract ( a + i + 1 ) from this position to count
code: res += upper_bound ( a + i , a + n , a [ i ] + mid ) - ( a + i + 1 ) ; return res ; }