Problem in upper_bound c++ stl

I am getting random values for ‘A’ each time

I am taking upper bound of arr(1 based index ) where c is length of array,arr2[z] element to be found.

A = upper_bound(arr+1,arr+c+1,arr2[z]) - (arr+1);

what is wrong in above statement?

Edit : I want to find upper_bound for an array.

Random value each time means that there are high chances of your program showing “undefined behaviour”, which might be due to violations of-

>Out of Index in an array/string Exception

>Using unintialized variables for array index etc.

>Taking input from both cin/scanf (same for output) after using 


I dont know the Q, or whole code, so i feel a bit clueless. Try checking the limits. Also, did you try checking the arr+c+1 line? If c is entire array length,why add 1 to it?


Upper_bound operates in [first,last) manner .
that’s why i added 1

he should add 1 as it is 1-indexed

Try to make some other alternative approach and check. Like, manual checking for last element before using this. An invalid argument in this function is known to cause undefined behavior. Just give it a try once, and get back to me. :slight_smile:

sometimes it happens because of compilers,once run your code and check on hackerrank

Hm, might be. My point is, is he absolutely sure that the error is on that specific line? It might be the error could be somewhere else where he didnt expect it.

should I subtract (arr) or (arr+1) ??

Try using the usual 0 based indexing once.

tried online compiler, 0 based indexing still problem persists.

you better use vector

ya that is a way but why is it not working with arrays?

make sure that A is an integer

long long int will not work??

yeah works

hey you need to substract arr not (arr+1)


see 30th in this code

Tried that!!


you should login to see that code.

anyway here is the code

@vijju123 is correct. There is probably some other error in your code. Otherwise, why don’t you give us an example where it doesn’t work? Give us a sample array and the search value.

Because this code works without problems:

#include <bits/stdc++.h>
int main()
    int c = 5;
    int arr[] = {-1, 2, 3, 6, 8, 9};
    int a = std::upper_bound(arr+1, arr+c+1, 6) - (arr + 1);
    std::cout << a << '\n';

It computes the index of the first number bigger than 6.
It returns the index zero-based. If you want the one-based index, then do - arr instead of - (arr + 1). But both versions run fine and don’t return “random” values.

1 Like