1

我想创建一个我输入的大小的位集,如下所示:

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. 我怎样才能解决这个问题?

*编辑:感谢那些帮助我的人,我想我知道我需要做什么。我可以创建一个大尺寸的位集,然后我可以忽略比我的输入长的位。

4

1 回答 1

1

简短的回答是,你不能。对于std::bitset,大小需要在编译时确定。见这里:https ://www.cplusplus.com/reference/bitset/bitset/

“位集的大小在编译时是固定的(由其模板参数确定)。对于还优化空间分配并允许动态调整大小的类,请参阅向量(向量)的布尔特化。”

这是向量专业化的链接: https ://www.cplusplus.com/reference/vector/vector-bool/

于 2021-06-29T15:17:43.350 回答