upper bounds and lower bounds

Hi guys I am reading the reference pages on cplusplus.com for lower and upper bounds,for lower bounds it says Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val.

and for upper bounds it says Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.


I'm not sure what is meant by this
> I'm not sure what is meant by this

The most effective way to increase your knowledge is to try new problems in a controlled way. Pick one aspect of C++ that you haven't understood before and write a program that, aside from using that one aspect, uses only things that you have already mastered. Then do what it takes to understand what your program is doing - and why. - Andrew Koenig and Barabara Moo in 'Ruminations on C++'.


So write a small program; something like this (the comments I've added is what you should be able to figure out on your own by playing around with such a program):

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

http://coliru.stacked-crooked.com/a/064901022c95e143
Topic archived. No new replies allowed.