本文介绍了C ++枚举标志与位集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
枚举标志上使用位集的利弊是什么?
What are pros/cons of usage bitsets over enum flags?
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;
}
正如我到目前为止所看到的,比特集具有更方便的置位/清除/翻转函数来处理,但是使用枚举标志是一种更广泛使用的方法。
As I can see so far, bitsets have more convinient set/clear/flip functions to deal with, but enum-flags usage is a more wide-spreaded approach.
比特集的缺点可能是什么?在日常代码中应使用什么时间? ?
What are possible downsides of bitsets and what and when should I use in my daily code?
推荐答案
您编译时启用了优化功能吗?
Do you compile with optimization on? It is very unlikely that there is a 24x speed factor.
对我来说,位集比较好,因为它可以为您管理空间:
To me, bitset is superior, because it manages space for you:
- 可以根据需要扩展。如果您有很多标志,则
int
/long long
版本的空间可能会用完。 - 可能会占用更少的空间,如果您仅使用几个标志(它可以放入
unsigned char
/unsigned简短的
-我不确定实现是否会应用此优化)
- can be extended as much as wanted. If you have a lot of flags, you may run out of space in the
int
/long long
version. - may take less space, if you only use just several flags (it can fit in an
unsigned char
/unsigned short
- I'm not sure that implementations apply this optimization, though)
这篇关于C ++枚举标志与位集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!