Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::ranges::take_view<V>::take_view

      From cppreference.com
      <cpp‎ |ranges‎ |take view
       
       
      Ranges library
      Range adaptors
       
       
      take_view() requiresstd::default_initializable<V>=default;
      (1)(since C++20)
      constexprexplicit take_view( V base,ranges::range_difference_t<V> count);
      (2)(since C++20)

      Constructs atake_view.

      1) Default constructor.Value-initializes the underlying viewbase_ and initializes thecount_ to0. After construction,base() returns a copy ofV() andsize() returns0.
      2) Initializes the underlying viewbase_ withstd::move(base) and thecount_ withcount. After construction,base() returns a copy ofbase andsize() returns the smaller ofcount andranges::size(base).

      [edit]Parameters

      base - the underlying view
      count - number of elements to take

      [edit]Example

      Prints firstn prime numbers that are generated usingSieve of Eratosthenes method.

      Run this code
      #include <bit>#include <bitset>#include <iomanip>#include <iostream>#include <limits>#include <ranges> constexprunsigned clog2(auto x)// ≈ ⌈ log₂(x) ⌉{returnstd::numeric_limits<decltype(x)>::digits-std::countl_zero(x);} template<unsigned Count>struct FirstPrimes{staticconstexprint count= Count; constexprbool operator()(int n)// is prime?{return n<2?false:               n==2?true:               n%2==0 or bits_.test(n/2)?false:true;}private:    constevalstaticauto init(){std::bitset<size_/2+1> bits;for(int n{3}; n< size_; n+=2)for(int i{n}, j{3}, k{};(k= i* j)< size_; j+=2)                bits.set(k/2);return bits;} // Keep only odd numbers; 0 means it is a primeconstexprstaticauto bits_{ init()}; // a(n) <= n * (log(n) + log(log(n)))staticconstexprint size_= Count*(clog2(Count)+ clog2(clog2(Count)));}; int main(){constexpr FirstPrimes<42> primes; auto primes_view= std::ranges::take_view{ std::views::iota(1)| std::views::filter(primes)                                             , primes.count}; std::cout<<"First "<< primes.count<<" prime numbers are:\n";for(int new_line{1};constint prime: primes_view)std::cout<<std::setw(3)<< prime<<(new_line++%7?' ':'\n');}

      Output:

      First 42 prime numbers are:  2   3   5   7  11  13  17 19  23  29  31  37  41  43 47  53  59  61  67  71  73 79  83  89  97 101 103 107109 113 127 131 137 139 149151 157 163 167 173 179 181

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      LWG 3714
      (P2711R1)
      C++20the multi-parameter constructor was not explicitmade explicit
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/ranges/take_view/take_view&oldid=173549"

      [8]ページ先頭

      ©2009-2025 Movatter.jp