多成员Constexpr结构初始化
Multiple Member Constexpr Struc Initialization
我是constexpr的新手,但我相信我正在练习的问题非常适合编译时计算。这不是为了家庭作业或其他什么,只是练习";现代的";C++
以下是我迄今为止所拥有的:标题(prime_app_lib.hpp(:
// #pragma once for modern header files (.hpp)
#pragma once
#include <math.h>
static constexpr unsigned max_prime = 10000U;
// check out this link for the number of primes: https://primes.utm.edu/howmany.html
static constexpr unsigned prime_array_size = 1230U;
constexpr unsigned get_nth_prime(unsigned n);
我正在尝试创建一个const数组(在编译时构造(,我可以使用get_nth_prime(n(访问它。你可以看到我试图用我选择的结构实现的算法。无论我尝试了什么,我都无法初始化isPrime和primeValue。我愿意接受任何建议,尤其是全面重写。我只想用一些好的、现代的C++。
#include "prime_app_lib.hpp"
#include <iostream>
struct PrimeData {
bool isPrime[max_prime];
unsigned primeValue[prime_array_size];
// Constructor for the data using SieveOfEratosthenes
// https://www.geeksforgeeks.org/program-to-find-the-nth-prime-number/
constexpr PrimeData() {
for (auto b : PrimeData::isPrime) {
b = true;
}
for (auto p : PrimeData::primeValue) {
p = 0;
}
for (int p = 2; p * p < max_prime; p++)
{
// If IsPrime[p] is not changed, then it is a prime
if (PrimeData::isPrime[p] == true)
{
// Update all multiples of p greater than or
// equal to the square of it
// numbers which are multiple of p and are
// less than p^2 are already been marked.
for (int i = p * p; i < max_prime; i += p)
PrimeData::isPrime[i] = false;
}
}
// Store all prime numbers
int n = 0;
for (int p = 2; p < max_prime; p++) {
if (PrimeData::isPrime[p] && n < prime_array_size)
PrimeData::primeValue[n] = static_cast<unsigned>(p);
}
}
};
// this was just to make sure I can get some constexpr compiling
constexpr unsigned get_nth_prime(unsigned n) {
return unsigned(prime_array_size);
}
int main() {
std::cout << prime_array_size << "n";
constexpr unsigned test1 = get_nth_prime(2);
static_assert(test1 == prime_array_size, "test1");
}
问题是,在进入构造函数主体之前,所有成员都需要初始化。所以你可以做:
constexpr PrimeData() : isPrime{} , primeValue{} {
// ...
}
或者简单地说:
struct PrimeData {
bool isPrime[max_prime]{};
unsigned primeValue[prime_array_size]{};
// ...
};
这是一个演示。
相关文章:
- 在C和C++中初始化结构中的数组
- 我们可以用参数化构造函数初始化结构的数组吗?
- 尝试初始化结构内的联合时出错
- 使用其他成员初始化结构的成员?
- 使用构造函数初始化结构还是在之后设置其值更好?
- 如果不初始化结构中的向量,它会自动为空还是具有随机内存位置的值?
- 如何在另一个结构中初始化结构数组?
- 如何在构造函数中初始化结构体的动态数组?
- 初始化结构中的联合 - c++
- 尝试初始化结构向量时出现编译错误
- 用于初始化结构的 void 指针强制转换
- 初始化结构的两种方式
- 使用用户定义的构造函数初始化C++结构
- 使用初始值设定项列表初始化结构,对于 std::array 失败
- 在 c++ 中初始化结构的指针
- 无序列图会创建一个零初始化结构吗?
- 如何在C++中初始化结构
- C 用结构指针初始化结构
- 在C 中初始化结构数组
- 使用数组聚合初始化结构数组