枚举标志上使用位集的优点/缺点是什么?
namespace Flag {
enum State {
Read = 1 << 0,
Write = 1 << 1,
Binary = 1 << 2,
};
}
namespace Plain {
enum State {
Read,
Write,
Binary,
Count
};
}
int main()
{
{
unsigned int state = Flag::Read | Flag::Binary;
std::cout << state << std::endl;
state |= Flag::Write;
state &= ~(Flag::Read | Flag::Binary);
std::cout << state << std::endl;
} {
std::bitset<Plain::Count> state;
state.set(Plain::Read);
state.set(Plain::Binary);
std::cout << state.to_ulong() << std::endl;
state.flip();
std::cout << state.to_ulong() << std::endl;
}
return 0;
}
到目前为止,正如我所看到的,位集有更方便的设置/清除/翻转功能来处理,但枚举标志的使用是一种更广泛使用的方法。
bitset 有哪些可能的缺点,我应该在日常代码中使用什么以及何时使用?
原文由 Nikolai Shalakin 发布,翻译遵循 CC BY-SA 4.0 许可协议
你编译优化了吗?几乎不可能有 24 倍的速度因子。
对我来说,bitset 更好,因为它为你管理空间:
int
/long long
版本中用完空间。unsigned char
/unsigned short
- 我不确定实现是否应用了这种优化)