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" ;
}
}
|