I want to create a collection of ASCII characters, at compile time, containing the alphabet.
Something like this works fine:
consteval std::string_view get_alphabet()
{
std::string_view sv = "ABCDE ... XYZ";
return sv;
}
However, to avoid typos, I would like to use iota to create the collection.
Is there a way I can populate some character collection, at compile time, and wrap it in a std::string_view ?
This is the idea, but it only works at runtime.
std::string_view get_alphabet()
{
static std::string s(26, 0);
std::iota(s.begin(), s.end(), 'A');
return s;
}
You can define a const array holding the alphabet like this:
#include <array>
constexpr auto get_alphabet()
{
return []<std::size_t...Is>(std::index_sequence<Is...>){
return std::array<char,26>{{ 'A'+ Is... }};
}(std::make_index_sequence<26>());
}
static_assert (get_alphabet() == std::array<char,26> { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' });
int main()
{
}
DEMO
Note that I made no typo while writing the static_assert ;)
As Konrad Rudolph pinpointed, one can also go directly for a std::string_view (requires c++23 though while the snippet above requires c++20 only)
#include <array>
#include <string_view>
constexpr auto get_alphabet ()
{
static constexpr std::array<char,26> arr = []<std::size_t...Is>(std::index_sequence<Is...>){
return std::array<char,26>{{ 'A'+ Is... }};
} (std::make_index_sequence<26>());
return std::string_view (arr.begin(),arr.end());
}
static_assert (get_alphabet().size() == 26);
static_assert (get_alphabet() == std::string_view { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });
int main() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With