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

14,191

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

#include<iostream>
#include<algorithm>
#include<vector>
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!!

Share:
14,191
Nodar Maruashvili
Author by

Nodar Maruashvili

Updated on June 04, 2022

Comments

  • Nodar Maruashvili
    Nodar Maruashvili almost 2 years

    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.

  • Pete Becker
    Pete Becker over 7 years
    You can use std::upper_bound and std::lower_bound directly on the array. There's no need for that vector.
  • marcbf
    marcbf over 5 years
    std::upper returns the first value greater than the sought one. If, for instance, you had sought for value 122 you would still get position 9 (or rather, 8), even though the value you looked for wasn't found.
  • marcbf
    marcbf about 4 years
    @Elliott No, it's actually as I wrote it. Have a look: en.cppreference.com/w/cpp/algorithm/upper_bound You're thinking of std::lower_bound which returns an iterator to either the value you're looking for or the one preceding it. For both std::lower_bound and std::upper_bound end() is returned if no suitable value could be found.