如何在不指定位大小的情况下将字符串转换为bitset ?
how do i convert a string a bitset without specifying size of bits?
我知道我们可以通过以下方式将字符串转换为bitset:
std::bitset<8> my_bitset(std::string("00011100");
,但是如果字符串被用户作为输入或来自某个文件,并且字符串的大小可能会发生变化,该怎么办?
在上面的例子中,我们知道string对象的大小是8,所以我们将bitset对象的大小初始化为8。我尝试传递字符串的大小,但得到编译错误。
这个问题可以更一般地改写为,"我如何使用运行时属性执行编译时生成的代码?"
基本答案是构建一个编译时指针数组,这些指针指向执行该工作的模板函数,然后索引到该数组。
#include <bitset>
#include <cstdint>
#include <array>
#include <utility>
// define the parameters of supported lengths
struct traits
{
static const std::size_t lowest = 1;
static const std::size_t highest = 64;
static const std::size_t extent = (highest - lowest) + 1;
};
//
// use a bitset of some length to decode the string
//
template<std::size_t Bits>
unsigned long long decode_impl(std::string const& s)
{
std::bitset<Bits> bs(s);
return bs.to_ullong();
}
//
// build an array of pointers to the decode functions, one for each Is
//
template<std::size_t...Is>
constexpr std::array<unsigned long long (*)(std::string const&), traits::extent>
decoders(std::index_sequence<Is...>)
{
return {{
&decode_impl<Is + traits::lowest>...
}};
}
//
// build all pointers
//
std::array<unsigned long long (*)(std::string const&), traits::extent>
constexpr decoders()
{
return decoders(std::make_index_sequence<traits::extent>());
}
//
// use runtime attributes to switch into compile-time constructs
//
unsigned long long decode(std::string const& s)
{
static constexpr auto my_decoders = decoders();
auto sz = std::max(s.size(), traits::lowest);
if (sz > traits::highest)
throw std::logic_error("unsupported length");
return my_decoders[sz - traits::lowest](s);
}
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 在不使用字符串库的情况下输入字符*
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何在不使用追加函数的情况下追加到字符串C++?
- 在这种情况下,使用 string_view 是否会导致不必要的字符串复制?
- 如何在不进行任何其他修改的情况下"pretty print" C++的XML字符串?
- 在不使用内置库函数的情况下添加字符串,我做错了什么?
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 有没有一种方法可以在不复制数据的情况下从string_view创建字符串流
- 如何在没有同步的情况下使用多个线程(2、4,8、16 个线程)在循环(10,100、1000 个周期)中打印字符串?
- 如何在没有映射的情况下在枚举和字符串之间进行转换?
- 如何在没有运算符>>的情况下从字符串流返回下一个令牌?
- 如何在不使用 STL 的情况下从函数反转字符串后返回字符串C++?
- 如何在不使用宽字符串的情况下创建目录C++?
- 如何在不迭代的情况下从string_view向量创建字符串向量?
- 如何在 C++03 中没有重复代码的情况下在堆栈上创建一个非常量 C 字符串数组?
- 如何在不复制的情况下比较字符串的一部分?
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)