Namespaces
Variants

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

来自 zh.cppreference.net
 
 
范围库
范围适配器
 
 
take_view() requires std::default_initializable<V> = default;
(1) (C++20 起)
constexpr explicit take_view( V base, ranges::range_difference_t<V> count );
(2) (C++20 起)

构造一个 take_view。

1) 默认构造函数。 值初始化底层视图 base_ 并将 count_ 初始化为 0。构造后,base() 返回 V() 的副本,size() 返回 0。
2) 用 base_ 初始化底层视图 std::move(base),并用 count_ 初始化 count。构造后,base() 返回 base 的副本,size() 返回 count 和 ranges::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 Count>
struct FirstPrimes
{
    static constexpr int count = Count;
    constexpr bool operator()(int n) // is prime?
    {
        return n < 2 ? false :
               n == 2 ? true :
               n % 2 == 0 or bits_.test(n / 2) ? false : true;
    }
private:
    consteval static auto 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 prime
    constexpr static auto bits_ { init() };
    // a(n) <= n * (log(n) + log(log(n)))
    static constexpr int 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}; const int prime : primes_view)
        std::cout << std::setw(3) << prime << (new_line++ % 7 ? ' ' : '\n');
}

输出:

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 107
109 113 127 131 137 139 149
151 157 163 167 173 179 181

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 3714
( P2711R1 )
C++20 多参数构造函数未声明为 explicit 改为 explicit