Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::lower_bound

      From cppreference.com
      <cpp‎ |algorithm
       
       
      Algorithm library
      Constrained algorithms and algorithms on ranges(C++20)
      Constrained algorithms, e.g.ranges::copy,ranges::sort, ...
      Execution policies(C++17)
      Sorting and related operations
      Partitioning operations
      Sorting operations
      Binary search operations
      (on partitioned ranges)
      lower_bound
      Set operations (on sorted ranges)
      Merge operations (on sorted ranges)
      Heap operations
      Minimum/maximum operations
      (C++11)
      (C++17)
      Lexicographical comparison operations
      Permutation operations
      C library
      Numeric operations
      Operations on uninitialized memory
       
      Defined in header<algorithm>
      (1)
      template<class ForwardIt,class T>

      ForwardIt lower_bound( ForwardIt first, ForwardIt last,

                             const T& value);
      (constexpr since C++20)
      (until C++26)
      template<class ForwardIt,class T=typenamestd::iterator_traits

                                               <ForwardIt>::value_type>
      constexpr ForwardIt lower_bound( ForwardIt first, ForwardIt last,

                                       const T& value);
      (since C++26)
      (2)
      template<class ForwardIt,class T,class Compare>

      ForwardIt lower_bound( ForwardIt first, ForwardIt last,

                             const T& value, Compare comp);
      (constexpr since C++20)
      (until C++26)
      template<class ForwardIt,class T=typenamestd::iterator_traits

                                               <ForwardIt>::value_type,
               class Compare>
      constexpr ForwardIt lower_bound( ForwardIt first, ForwardIt last,

                                       const T& value, Compare comp);
      (since C++26)

      Searches for the first element in the partitioned range[firstlast) which isnot ordered beforevalue.

      1) The order is determined byoperator<:

      Returns the first iteratoriter in[firstlast) wherebool(*iter< value) isfalse, orlast if no suchiter exists.

      If the elementselem of[firstlast) are notpartitioned with respect to the expressionbool(elem< value), the behavior is undefined.

      (until C++20)

      Equivalent tostd::lower_bound(first, last, value,std::less{}).

      (since C++20)
      2) The order is determined bycomp:
      Returns the first iteratoriter in[firstlast) wherebool(comp(*iter, value)) isfalse, orlast if no suchiter exists.
      If the elementselem of[firstlast) are notpartitioned with respect to the expressionbool(comp(elem, value)), the behavior is undefined.

      Contents

      [edit]Parameters

      first, last - the pair of iterators defining the partitionedrange of elements to examine
      value - value to compare the elements to
      comp - binary predicate which returns ​true if the first argument is ordered before the second.

      The signature of the predicate function should be equivalent to the following:

       bool pred(const Type1&a,const Type2&b);

      While the signature does not need to haveconst&, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const)Type1 andType2 regardless ofvalue category (thus,Type1& is not allowed, nor isType1 unless forType1 a move is equivalent to a copy(since C++11)).
      The typeType1 must be such that an object of typeForwardIt can be dereferenced and then implicitly converted toType1. The typeType2 must be such that an object of typeT can be implicitly converted toType2.​

      Type requirements
      -
      ForwardIt must meet the requirements ofLegacyForwardIterator.
      -
      Compare must meet the requirements ofBinaryPredicate. It is not required to satisfyCompare.

      [edit]Return value

      Iterator to the first element of the range[firstlast) not ordered beforevalue, orlast if no such element is found.

      [edit]Complexity

      Given\(\scriptsize N\)N asstd::distance(first, last):

      1) At most\(\scriptsize \log_{2}(N)+O(1)\)log2(N)+O(1) comparisons withvalue usingoperator<(until C++20)std::less{}(since C++20).
      2) At most\(\scriptsize \log_{2}(N)+O(1)\)log2(N)+O(1) applications of the comparatorcomp.

      However, ifForwardIt is not aLegacyRandomAccessIterator, the number of iterator increments is linear in\(\scriptsize N\)N. Notably,std::map,std::multimap,std::set, andstd::multiset iterators are not random access, and so their memberlower_bound functions should be preferred.

      [edit]Possible implementation

      See also the implementations inlibstdc++ andlibc++.

      lower_bound (1)
      template<class ForwardIt,class T=typenamestd::iterator_traits<ForwardIt>::value_type>ForwardIt lower_bound(ForwardIt first, ForwardIt last,const T& value){return std::lower_bound(first, last, value,std::less{});}
      lower_bound (2)
      template<class ForwardIt,class T=typenamestd::iterator_traits<ForwardIt>::value_type,class Compare>ForwardIt lower_bound(ForwardIt first, ForwardIt last,const T& value, Compare comp){    ForwardIt it;typenamestd::iterator_traits<ForwardIt>::difference_type count, step;    count=std::distance(first, last); while(count>0){        it= first;        step= count/2;std::advance(it, step); if(comp(*it, value)){            first=++it;            count-= step+1;}else            count= step;} return first;}

      [edit]Notes

      Althoughstd::lower_bound only requires[firstlast) to be partitioned, this algorithm is usually used in the case where[firstlast) is sorted, so that the binary search is valid for anyvalue.

      Unlikestd::binary_search,std::lower_bound does not requireoperator< orcomp to be asymmetric (i.e.,a< b andb< a always have different results). In fact, it does not even requirevalue<*iter orcomp(value,*iter) to be well-formed for any iteratoriter in[firstlast).

      Feature-test macroValueStdFeature
      __cpp_lib_algorithm_default_value_type202403(C++26)List-initialization for algorithms(1,2)

      [edit]Example

      Run this code
      #include <algorithm>#include <cassert>#include <complex>#include <iostream>#include <vector> struct PriceInfo{double price;}; int main(){conststd::vector<int> data{1,2,4,5,5,6}; for(int i=0; i<8;++i){// Search for first element x such that i ≤ xauto lower= std::lower_bound(data.begin(), data.end(), i); std::cout<< i<<" ≤ ";        lower!= data.end()?std::cout<<*lower<<" at index "<<std::distance(data.begin(), lower):std::cout<<"not found";std::cout<<'\n';} std::vector<PriceInfo> prices{{100.0},{101.5},{102.5},{102.5},{107.3}}; for(constdouble to_find:{102.5,110.2}){auto prc_info= std::lower_bound(prices.begin(), prices.end(), to_find,[](const PriceInfo& info,double value){return info.price< value;});         prc_info!= prices.end()?std::cout<< prc_info->price<<" at index "<< prc_info- prices.begin():std::cout<< to_find<<" not found";std::cout<<'\n';} using CD=std::complex<double>;std::vector<CD> nums{{1,0},{2,2},{2,1},{3,0}};auto cmpz=[](CD x, CD y){return x.real()< y.real();};#ifdef __cpp_lib_algorithm_default_value_typeauto it= std::lower_bound(nums.cbegin(), nums.cend(),{2,0}, cmpz);#elseauto it= std::lower_bound(nums.cbegin(), nums.cend(), CD{2,0}, cmpz);#endifassert((*it== CD{2,2}));}

      Output:

      0 ≤ 1 at index 01 ≤ 1 at index 02 ≤ 2 at index 13 ≤ 4 at index 24 ≤ 4 at index 25 ≤ 5 at index 36 ≤ 6 at index 57 ≤ not found102.5 at index 2110.2 not found

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 270C++98Compare was required to satisfyCompare andT was required
      to beLessThanComparable (strict weak ordering required)
      only a partitioning is required;
      heterogeneous comparisons permitted
      LWG 384C++98at most\(\scriptsize \log(N)+1\)log(N)+1 comparisons were allowedcorrected to\(\scriptsize \log_{2}(N)+O(1)\)log2(N)+1
      LWG 2150C++98if any iteratoriter exists in[firstlast) such that
      bool(comp(*iter, value)) isfalse,std::lower_bound
      could return any iterator in[iterlast)
      no iterator after
      iter can be returned

      [edit]See also

      returns range of elements matching a specific key
      (function template)[edit]
      divides a range of elements into two groups
      (function template)[edit]
      locates the partition point of a partitioned range
      (function template)[edit]
      returns an iterator to the first elementgreater than a certain value
      (function template)[edit]
      returns an iterator to the first elementnot less than the given key
      (public member function ofstd::set<Key,Compare,Allocator>)[edit]
      returns an iterator to the first elementnot less than the given key
      (public member function ofstd::multiset<Key,Compare,Allocator>)[edit]
      returns an iterator to the first elementnot less than the given value
      (algorithm function object)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/lower_bound&oldid=180628"

      [8]ページ先頭

      ©2009-2025 Movatter.jp