问题描述
我想用我输入的大小创建一个位集,如下所示:
int a;
int main() {
cin >> a;
const int l = a;
cout << bitset<l>(123);
}
jdoodle.cpp:11:21: error: the value of ‘l’ is not usable in a constant expression
11 | cout << bitset<l>(123);
| ^
jdoodle.cpp:6:11: note: ‘l’ was not initialized with a constant expression
6 | const int l = a;
| ^
jdoodle.cpp:11:21: note: in template argument for type ‘long unsigned int’
11 | cout << bitset<l>(123);
当我将 l
设置为诸如 const int l = 6
之类的整数时它工作正常,但是当我将其更改为 const int l = a
时出现错误。我该如何解决这个问题?
*编辑:感谢那些帮助我的人,我想我知道我需要做什么了。我可以创建一个大尺寸的位集,然后我可以忽略比输入长的位。
解决方法
简短的回答是,你不能。对于 std::bitset
,需要在编译时确定大小。请参阅此处:https://www.cplusplus.com/reference/bitset/bitset/
“位集的大小在编译时是固定的(由其模板参数决定)。对于同样针对空间分配进行优化并允许动态调整大小的类,请参阅向量(vector)的 bool 特化。”
这是向量专业化的链接: https://www.cplusplus.com/reference/vector/vector-bool/