为什么在 C++ 中使用 char 数组而不是 int 作为位集?
对于我正在从事的项目,我需要为位集创建自己的实现。我查看了 STL 库以了解他们如何处理此问题,并在网上查看了其他一些内容。使用 char 数组似乎是相当标准的。为什么每个人都使用字符数组而不是整数类型,这是有原因的吗?
For a project I'm working on I need to create my own implementation for a bitset. I've taken a look at the STL library to see how they handle this and looked at a few other things online. It seems like it's pretty standard to use a char array. Is there a reason why everyone uses char arrays instead of the integer type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅仅因为 C++ 中的
char
是单个字节,(或者至少 C++ 标准保证它的大小小于或等于int
或Short
),而int
的大小通常大于字节。 (现在大多数机器上通常是 32 位或 4 字节。)由于单个字节是计算机可以处理的最小可寻址数据单元,因此很自然地使用char
数组当使用单独的位时。例如,如果您使用int
,那么您将浪费大量空间来存储不是sizeof(int)
倍数的任何位数,但使用字节数组时,您将浪费大量空间。浪费尽可能少的空间。Simply because a
char
in C++ is a single byte, (or at least, it's guaranteed by the C++ standard to be less than or equal in size toint
orshort
) whereas the size of anint
is usually larger than a byte. (It's usually 32-bit, or 4-bytes, on most machines these days.) Since a single byte is the smallest addressable unit of data a computer can process, it's natural to use arrays ofchar
s when working with individual bits. If you usedint
, for example, then you would waste significant space for any number of bits that is not a multiple ofsizeof(int)
, but with a byte array you waste the least amount of space possible.Char(通常)是微处理器可以操作的最小位单位。如果您要创建一个可处理任意位数的对象,则使用最小单位的数组是有意义的。这样您始终可以使用尽可能少的单位。
如果您需要非任意大小的位集,并且处理器具有足够大的本机类型来包含它,请使用 N 位类型。它会比数组更有效率。
Char is (usually) the smallest unit of bits that a microprocessor can manipulate. If you're creating an object that works with arbitrary numbers of bits, it makes sense to use an array of the smallest unit. That way you always use the fewest units possible.
If you need a non-arbitrary-sized bitset and the processor has a native type large enough to contain it, use an N-bit type. It will be more efficient than an array.