枚举标志上使用位集的利弊是什么?
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;
}
到目前为止,正如我所看到的,位集具有更方便的set/clear/flip函数来处理,但是enum-flags的使用是一种更为广泛的方法。
比特集可能有什么弊端?我应该在每日代码中使用什么时间?
最佳答案
您是否进行了优化编译? 24倍速是极不可能的。
对我来说,位集是优越的,因为它可以为您管理空间:
int
/long long
版本中的空间可能用完了。 unsigned char
/unsigned short
-不过我不确定实现是否应用此优化),则可能会占用较少的空间。