Lower bound works as an upper bound ..

this outputs 15 not 7


1
2
3
4
5
6
7
  #include<iostream>
#include<algorithm>
using namespace std;
int main(){
 int a[]= {7,15};
 cout<<a[lower_bound(a,a+2,10)-a]<<endl;
}
The reason is this:

http://www.cplusplus.com/reference/algorithm/lower_bound/?kw=lower_bound

Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.
oh can i change that ?? or should i make the function of binary search to return the position ?
can i change that

Sure, but change it to what? What, precisely, are you looking for?

Whatever it is, you can probably use lower_bound() or upper_bound() to get an item adjacent to what you want, so write a function that calls one of these and then adjusts the iterator as needed.

When I've written functions like this, I've called then findLEQ, findGT, findGEQ, etc. for finding the closest item that's <=, >, >= respectively.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    const int a[] = { 1, 3, 3, 5, 5, 5, 7, 8, 8, 9 } ;
    for( int v : a ) std::cout << v << ' ' ;
    std::cout << '\n' ;

    for( const int value : { 4, 5 } )
    {
        // check if the value is present in the ordered sequence
        std::cout << std::boolalpha
                  << "\nvalue " << value << " is present in the sequence? "
                  << std::binary_search( std::begin(a), std::end(a), value ) << '\n' ;

        // locate the position(s) of a value in the ordered sequence
        // equal_range returns the pair (lower_bound,upper_bound)
        // http://en.cppreference.com/w/cpp/algorithm/equal_range
        const auto pair = std::equal_range( std::begin(a), std::end(a), value ) ;

        if( pair.first != pair.second ) // lower_bound != upper_bound; at least one was found
        {
            std::cout << std::distance( pair.first, pair.second )
                      << " occurrences of value " << value << " were found starting at position "
                      << std::distance( std::begin(a), pair.first ) << '\n' ;
        }

        else // lower_bound == upper_bound; value was not found
            std::cout << "the value " << value << " is not present in the sequence\n" ;
    }
}

http://rextester.com/PGEIO91732
Topic archived. No new replies allowed.