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

来自cppreference.com
< cpp‎ | ranges‎ | take view
 
 
 
 
take_view() requires std::default_initializable<V> = default;
(1) (C++20 起)
constexpr take_view( V base, ranges::range_difference_t<V> count );
(2) (C++20 起)

构造 take_view

1) 默认构造函数。值初始化底层视图并初始化计数为 0 。构造后 base() 返回 V() 的副本而 size() 返回 0
2)std::move(base) 初始化底层视图并以 count 初始化计数。构造后 base() 返回 base 的副本而 size() 返回 countranges::size(base) 的较小者。

参数

base - 底层视图
count - 要收取的元素数

示例

打印首 n 个质数,用埃拉托色尼筛法生成起始。

#include <bit>
#include <bitset>
#include <iomanip>
#include <iostream>
#include <limits>
#include <ranges>
 
constexpr unsigned clog2(auto x) // ~ ⌈ log₂(x) ⌉
{
    return std::numeric_limits<decltype(x)>::digits - std::countl_zero(x);
}
 
template <unsigned Primes> struct Sieve
{
    bool operator()(int n) {
        if (n < 2) return false;
        if (n == 2) return true;
        if (n % 2 == 0 || bits.test(n / 2))
            return false;
        for (int i{n}, j{3}, k{}; (k = i * j) < size; j += 2)
            bits.set(k / 2);
        return true;
    }
 
    static constexpr int prime_numbers = Primes;
 
    // a(n) ~= n*(log(n) + log(log(n)));
    static constexpr int size = Primes*(clog2(Primes) + clog2(clog2(Primes)));
 
    // 仅保留奇数; 0 意味着它是质数
    private: std::bitset<size / 2 + 1> bits;
};
 
int main()
{
    Sieve<100> sieve{};
    auto primes_gen = std::views::iota(1)
                    | std::views::filter(sieve);
 
    auto primes = std::ranges::take_view{ primes_gen, sieve.prime_numbers };
 
    for (int n{1}; auto prime : primes) {
        std::cout << prime << (n++ % 10 ? ' ' : '\n');
    }
 
    std::cout
        << "\n" "sieve.prime_numbers: " << sieve.prime_numbers
        << "\n" "sieve.size: " << sieve.size
        << "\n" "sizeof(sieve): " << sizeof sieve << " bytes\n";
}

输出:

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 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
 
sieve.prime_numbers: 100
sieve.size: 1000
sizeof(sieve): 64 bytes