Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::upper_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)
      upper_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 upper_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 upper_bound( ForwardIt first, ForwardIt last,

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

      ForwardIt upper_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 upper_bound( ForwardIt first, ForwardIt last,

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

      Searches for the first element in the partitioned range[firstlast) which is ordered aftervalue.

      1) The order is determined byoperator<:

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

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

      (until C++20)

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

      (since C++20)
      2) The order is determined bycomp:
      Returns the first iteratoriter in[firstlast) wherebool(comp(value,*iter)) istrue, orlast if no suchiter exists.
      If the elementselem of[firstlast) are notpartitioned with respect to the expressionbool(comp(value, elem)), 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 typeT can be implicitly converted toType1. The typeType2 must be such that an object of typeForwardIt can be dereferenced and then 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) ordered aftervalue, 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 memberupper_bound functions should be preferred.

      [edit]Possible implementation

      See also the implementations inlibstdc++ andlibc++.

      upper_bound (1)
      template<class ForwardIt,class T=typenamestd::iterator_traits<ForwardIt>::value_type>ForwardIt upper_bound(ForwardIt first, ForwardIt last,const T& value){return std::upper_bound(first, last, value,std::less{});}
      upper_bound (2)
      template<class ForwardIt,class T=typenamestd::iterator_traits<ForwardIt>::value_type,class Compare>ForwardIt upper_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(value,*it)){            first=++it;            count-= step+1;}else            count= step;} return first;}

      [edit]Notes

      Althoughstd::upper_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.

      For any iteratoriter in[firstlast),std::upper_bound requiresvalue<*iter andcomp(value,*iter) to be well-formed, whilestd::lower_bound requires*iter< value andcomp(*iter, value) to be well-formed instead.

      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<7;++i){// Search first element that is greater than iauto upper= std::upper_bound(data.begin(), data.end(), i); std::cout<< i<<" < ";        upper!= data.end()?std::cout<<*upper<<" at index "<<std::distance(data.begin(), upper):std::cout<<"not found";std::cout<<'\n';} std::vector<PriceInfo> prices{{100.0},{101.5},{102.5},{102.5},{107.3}}; for(double to_find:{102.5,110.2}){auto prc_info= std::upper_bound(prices.begin(), prices.end(), to_find,[](double value,const PriceInfo& info){return value< info.price;});         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},{3,1}};auto cmpz=[](CD x, CD y){return x.real()< y.real();};#ifdef __cpp_lib_algorithm_default_value_typeauto it= std::upper_bound(nums.cbegin(), nums.cend(),{2,0}, cmpz);#elseauto it= std::upper_bound(nums.cbegin(), nums.cend(), CD{2,0}, cmpz);#endifassert((*it== CD{3,0}));}

      Output:

      0 < 1 at index 01 < 2 at index 12 < 4 at index 23 < 4 at index 24 < 5 at index 35 < 6 at index 56 < not found 107.3 at index 4110.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\)log2(N)+1 comparisons were allowedcorrected to\(\scriptsize \log_{2}(N)+O(1)\)log2(N)+O(1)
      LWG 577C++98last could not be returnedallowed
      LWG 2150C++98if any iteratoriter exists in[firstlast) such that
      bool(comp(value,*iter)) istrue,std::upper_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]
      returns an iterator to the first elementnot less than the given value
      (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
      (algorithm function object)[edit]
      returns an iterator to the first elementgreater than the given key
      (public member function ofstd::set<Key,Compare,Allocator>)[edit]
      returns an iterator to the first elementgreater than the given key
      (public member function ofstd::multiset<Key,Compare,Allocator>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/upper_bound&oldid=180595"

      [8]ページ先頭

      ©2009-2025 Movatter.jp