So I've been looking around and trying different things but I can't wrap my head around how I would go about creating some collection of strings with constexpr.
What I'm trying to do is basically the following, which obviously doesn't compile:
constexpr std::vector<std::string> fizzbuzz(){
size_t N = 100;
std::vector<std::string> result;
result.reserve(N);
for (int i = 0; i < N; i++){
int k = i+1;
if(k % 5 == 0 && k % 3 == 0){
result.push_back("FizzBuzz");
}
else if(k % 5 == 0){
result.push_back("Buzz");
}
else if(k % 3 == 0){
result.push_back("Fizz");
}
else{
result.push_back(std::to_string(k));
}
}
return result;
}
I would already be happy if I understood how to do something as simple as:
constexpr std::string fizzbuzz(int k){
if(k % 3 == 0) return "Fizz";
else return std::to_string(k);
}
From there I reckon it's only a small step to the complete solution. It doesn't have to be std::strings it doesn't have to be std::vectors.
Oh, and the lower the C++Standard the better.
Edited to help understanding the problem better.
std::vector/std::stringdoesn't have constexpr constructor (before C++20)...std::arrayandstd::string_viewhave.