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
|
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
const std::vector<int> seq { 0, 1, 2, 2, 2, 3, 3, 4, 4 } ;
const auto lb = std::lower_bound( std::begin(seq), std::end(seq), 2 ) ;
// returns an iterator 'pointing' to the first 2 (first element not less than 2)
// { 0, 1, 2, 2, 2, 3, 3, 4, 4 }
// ^
// |
for( auto iter = lb ; iter != std::end(seq) ; ++iter ) std::cout << *iter << ' ' ; // 2 2 2 3 3 4 4
std::cout << '\n' ;
const auto ub = std::upper_bound( std::begin(seq), std::end(seq), 2 ) ;
// returns an iterator 'pointing' to the first 3 (first element greater than 2)
// { 0, 1, 2, 2, 2, 3, 3, 4, 4 }
// ^
// |
for( auto iter = ub ; iter != std::end(seq) ; ++iter ) std::cout << *iter << ' ' ; // 3 3 4 4
std::cout << '\n' ;
const auto[ lb1, ub1 ] = std::equal_range( std::begin(seq), std::end(seq), 2 ) ; // C++17 (structured binding)
// returns a pair of iterators { lower bound, upper bound }
for( auto iter = lb1 ; iter != ub1 ; ++iter ) std::cout << *iter << ' ' ; // 2 2 2
std::cout << '\n' ;
}
|