Fennix Fennix - 1 year ago 120
C++ Question

How to use lower_bound(upper_bound) to find position of any number in array?

For example, I have an array with elements 1,7,9,23,34,47,67,89,123,234,345,567.
I need to know the position of 123.

Answer Source

Declare and initialize the array with the elements. Then create a vector of ints. Use upper_bound() on the vector. Here is an example:

using namespace std;

int main() {
    int arr[] = {1,7,9,23,34,47,67,89,123,234,345,567};
    int len = sizeof(arr)/sizeof(arr[0]);
    vector<int> v(arr,arr+len);

    vector<int>::iterator upper;
    upper = upper_bound(v.begin(), v.end(), 123);
    cout<<(upper-v.begin())<<endl;  // Output: 9

    return 0;

Hope it helps!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download