std::ranges...w::take_view(3)
β¨ NAME β¨
okay so bestie, this is the std::ranges...w::take_view(3) page from the C++ Standard Libary manual, and the main character is literally std::ranges::take_view::take_view β std::ranges::take_view::take_view. yes, that's the whole NAME. constructor energy only. π
πΈ Synopsis πΈ
take_view() requires std::default_initializable<V> = default;
(1) (since C++20)
constexpr explicit take_view( V base,
(2) (since C++20)
ranges::range_difference_t<V> count );
π Parameters π
baseβ the underlying view π«Άcountβ number of elements to take π’
π¦ Example π¦
Prints first n prime numbers that are generated using Sieve of Eratosthenes method. (yes, that is the whole vibe, no cap.)
#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');
}
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 107
109 113 127 131 137 139 149
151 157 163 167 173 179 181
π₯ Defect reports π₯
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
- DR:
LWG 3714(P2711R1) β Applied to:C++20β Behavior as published: the multi-parameter constructor was not made explicit β Correct behavior:explicit.
mwah π this iconic page is brought to you by http://cppreference.com, version/date 2024.06.10, and it's the std::ranges...w::take_view(3) page. byeee π«Άπ
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms