rationale for std::lower_bound and std::upper_bound?

后端 未结 10 1536
傲寒
傲寒 2021-01-30 08:13

STL provides binary search functions std::lower_bound and std::upper_bound, but I tend not to use them because I\'ve been unable to remember what they do, because their contract

10条回答
  •  梦谈多话
    2021-01-30 08:55

    Consider the sequence

    1 2 3 4 5 6 6 6 7 8 9

    lower bound for 6 is the position of the first 6.

    upper bound for 6 is the position of the 7.

    these positions serve as common (begin, end) pair designating the run of 6-values.


    Example:

    #include 
    #include 
    #include 
    using namespace std;
    
    auto main()
        -> int
    {
        vector v = {1, 2, 3, 4, 5, 6, 6, 6, 7, 8, 9};
        auto const pos1 = lower_bound( v.begin(), v.end(), 6 );
        auto const pos2 = upper_bound( v.begin(), v.end(), 6 );
        for( auto it = pos1; it != pos2; ++it )
        {
            cout << *it;
        }
        cout << endl;
    }
    

提交回复
热议问题