Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::count,std::count_if

      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)
      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 InputIt,class T>

      typenamestd::iterator_traits<InputIt>::difference_type

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

                                             <InputIt>::value_type>
      constexprtypenamestd::iterator_traits<InputIt>::difference_type

          count( InputIt first, InputIt last,const T& value);
      (since C++26)
      (2)
      template<class ExecutionPolicy,class ForwardIt,class T>

      typenamestd::iterator_traits<ForwardIt>::difference_type
          count( ExecutionPolicy&& policy,

                 ForwardIt first, ForwardIt last,const T& value);
      (since C++17)
      (until C++26)
      template<class ExecutionPolicy,

               class ForwardIt,class T=typenamestd::iterator_traits
                                               <ForwardIt>::value_type>
      typenamestd::iterator_traits<ForwardIt>::difference_type
          count( ExecutionPolicy&& policy,

                 ForwardIt first, ForwardIt last,const T& value);
      (since C++26)
      template<class InputIt,class UnaryPred>

      typenamestd::iterator_traits<InputIt>::difference_type

          count_if( InputIt first, InputIt last, UnaryPred p);
      (3)(constexpr since C++20)
      template<class ExecutionPolicy,class ForwardIt,class UnaryPred>

      typenamestd::iterator_traits<ForwardIt>::difference_type
          count_if( ExecutionPolicy&& policy,

                    ForwardIt first, ForwardIt last, UnaryPred p);
      (4)(since C++17)

      Returns the number of elements in the range[firstlast) satisfying specific criteria.

      1) Counts the elements that are equal tovalue (usingoperator==).
      3) Counts elements for which predicatep returnstrue.
      2,4) Same as(1,3), but executed according topolicy.
      These overloads participate in overload resolution only if all following conditions are satisfied:

      std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> istrue.

      (until C++20)

      std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> istrue.

      (since C++20)

      Contents

      [edit]Parameters

      first, last - the pair of iterators defining therange of elements to examine
      value - the value to search for
      policy - theexecution policy to use
      p - unary predicate which returns ​true for the required elements.

      The expressionp(v) must be convertible tobool for every argumentv of type (possibly const)VT, whereVT is the value type ofInputIt, regardless ofvalue category, and must not modifyv. Thus, a parameter type ofVT&is not allowed, nor isVT unless forVT a move is equivalent to a copy(since C++11).​

      Type requirements
      -
      InputIt must meet the requirements ofLegacyInputIterator.
      -
      ForwardIt must meet the requirements ofLegacyForwardIterator.
      -
      UnaryPred must meet the requirements ofPredicate.

      [edit]Return value

      The number of iteratorsit in therange[firstlast) satisfying the following condition:

      1,2)*it== value istrue.
      3,4)p(*it)!=false istrue.

      [edit]Complexity

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

      1,2) Exactly\(\scriptsize N\)N comparisons withvalue usingoperator==.
      3,4) Exactly\(\scriptsize N\)N applications of the predicatep.

      [edit]Exceptions

      The overloads with a template parameter namedExecutionPolicy report errors as follows:

      • If execution of a function invoked as part of the algorithm throws an exception andExecutionPolicy is one of thestandard policies,std::terminate is called. For any otherExecutionPolicy, the behavior is implementation-defined.
      • If the algorithm fails to allocate memory,std::bad_alloc is thrown.

      [edit]Notes

      For the number of elements in the range[firstlast) without any additional criteria, seestd::distance.

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

      [edit]Possible implementation

      See also the implementations ofcount inlibstdc++ andlibc++.

      See also the implementations ofcount_if inlibstdc++ andlibc++.


      count (1)
      template<class InputIt,class T=typenamestd::iterator_traits<InputIt>::value_type>typenamestd::iterator_traits<InputIt>::difference_type    count(InputIt first, InputIt last,const T& value){typenamestd::iterator_traits<InputIt>::difference_type ret=0;for(; first!= last;++first)if(*first== value)++ret;return ret;}
      count_if (3)
      template<class InputIt,class UnaryPred>typenamestd::iterator_traits<InputIt>::difference_type    count_if(InputIt first, InputIt last, UnaryPred p){typenamestd::iterator_traits<InputIt>::difference_type ret=0;for(; first!= last;++first)if(p(*first))++ret;return ret;}

      [edit]Example

      Run this code
      #include <algorithm>#include <array>#include <cassert>#include <complex>#include <iostream>#include <iterator> int main(){constexprstd::array v{1,2,3,4,4,3,7,8,9,10};std::cout<<"v: ";std::copy(v.cbegin(), v.cend(),std::ostream_iterator<int>(std::cout," "));std::cout<<'\n'; // Determine how many integers match a target value.for(constint target:{3,4,5}){constint num_items= std::count(v.cbegin(), v.cend(), target);std::cout<<"number: "<< target<<", count: "<< num_items<<'\n';} // Use a lambda expression to count elements divisible by 4.int count_div4= std::count_if(v.begin(), v.end(),[](int i){return i%4==0;});std::cout<<"numbers divisible by four: "<< count_div4<<'\n'; // A simplified version of `distance` with O(N) complexity:auto distance=[](auto first,auto last){return std::count_if(first, last,[](auto){returntrue;});};    static_assert(distance(v.begin(), v.end())==10); std::array<std::complex<double>,3> nums{{{4,2},{1,3},{4,2}}};#ifdef __cpp_lib_algorithm_default_value_type// T gets deduced making list-initialization possibleauto c= std::count(nums.cbegin(), nums.cend(),{4,2});#elseauto c= std::count(nums.cbegin(), nums.cend(),std::complex<double>{4,2});#endifassert(c==2);}

      Output:

      v: 1 2 3 4 4 3 7 8 9 10number: 3, count: 2number: 4, count: 2number: 5, count: 0numbers divisible by four: 3

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      LWG 283C++98T was required to beEqualityComparable, but
      the value type ofInputIt is not alwaysT
      removed the requirement

      [edit]See also

      returns the distance between two iterators
      (function template)[edit]
      returns the number of elements satisfying specific criteria
      (algorithm function object)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/algorithm/count&oldid=180618"

      [8]ページ先頭

      ©2009-2025 Movatter.jp