[英]Is using unsigned int instead of std::vector<bool> or std::bitset a recommended practice?
I've seen some coding examples that recommend using an unsigned int
to represent a bitmap: 我已经看到一些编码示例,建议使用
unsigned int
来表示位图:
unsigned int zero_rows {0};
for (auto i = 0; i < n_rows; ++i) {
zero_rows |= (1 << i);
…
}
Does this provide any benefit over using std::vector<bool>
: 这是否比使用
std::vector<bool>
提供了任何好处:
std::vector<bool> zero_rows(n_rows, false);
for (auto i = 0; i < n_rows; ++i) {
zero_rows[i] = true;
…
}
Another option I guess could be std::bitset
, but I'm not really sure about the pros and cons of each yet. 我猜的另一个选择可能是
std::bitset
,但我还不确定每个选项的优缺点。 I'd just like to know what is the recommended practice. 我想知道推荐的做法是什么。
The use of some size of unsigned integer to represent a fixed-size sequence of bits was the only option in C++ before the 1998 Standard, when std::vector<bool>
and std::bitset
were introduced. 使用一些大小的无符号整数来表示固定大小的位序列是1998年标准之前C ++中唯一的选项,当时引入了
std::vector<bool>
和std::bitset
。 The practice was inherited from C, in which it is considered a competent programmer's proficiency and it remains so considered in C++. 这种做法继承自C,它被认为是一个称职的程序员的熟练程度,并且在C ++中仍然如此考虑。
std::vector<bool>
has come to be regarded with regret. std::vector<bool>
已经被遗憾地看待了。 See eg vector<bool>
: More Problems, Better Solutions and Effective STL Item 18 . 参见例如
vector<bool>
:更多问题,更好的解决方案和有效的STL项目18 。 std:::bitset
is considered fit for purpose. std:::bitset
被认为适合用途。
The unsigned integer practice inherently represents a hand-rolled simulation of of a fixed-size bit-sequence by overt artifice, constrained and complicated by the fact that there are only a few sizes of unsigned integer (even if the chosen size is made precise). 无符号整数实践固有地表示通过明显技巧对固定大小的比特序列进行手动模拟,由于只有几个无符号整数的大小(即使所选大小精确),也会受到限制和复杂化。 。 If you require a fixed-size bit-sequence to be subject to operations that are all supported by the interface of
std::bitset
then other things being equal the Standard Library's provision is to be preferred to hand-rolled code for the all of the reasons to which the Library owes its existence. 如果你需要一个固定大小的比特序列来接受
std::bitset
接口所支持的操作,那么其他条件相同的标准库的规定是首选的手动代码为所有的图书馆存在的原因。
You must be the judge whether, in the context of your application, other things are equal. 在申请的情况下,你必须判断其他事情是否平等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.