c++ - 在 C++ 中高效使用 bool 值 true 和 false?

标签 c++ memory optimization compiler-construction storage

是否有任何编译器专家能够评论 bool 值的有效使用?具体来说,编译器是否能够优化 std::vector<boolean>使用最少的内存?是否有等效的数据结构?

过去,有些语言的编译器可以将 bool 数组压缩为每个 bool 值仅表示一位。也许对 C++ 可以做的最好的事情是使用 std::vector<char>以最小的内存使用量存储 bool 值?

此处的用例将存储数亿个 bool 值,其中单个字节将节省大量空间,超过每个值 4 个或更多字节和一个位,甚至更多。

最佳答案

参见 std::vector

Specializations

The standard library provides a specialization of std::vector for the type bool, which is optimized for space efficiency.
vector<bool> space-efficient dynamic bitset (class template specialization)

来自“C++ 工作草案,2012-11-02”

23.3.7 Class vector [vector.bool]
1 To optimize space allocation, a specialization of vector for bool elements is provided:
template <class Allocator> class vector<bool, Allocator> {
...
}

3 There is no requirement that the data be stored as a contiguous allocation of bool values. A space-optimized representation of bits is recommended instead.

因此没有要求,只是建议将 bool 值存储为位。

关于c++ - 在 C++ 中高效使用 bool 值 true 和 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15126881/

相关文章:

C++ 转换为更精确的类型并失去准确性?

C++ 通过引用传递的参数也通过引用接收

静态 vs 函数静态 vs 成员函数静态的 C++ 内存布局

arrays - C2 JIT 编译器何时触发 Java 循环谓词优化?

c++ - 为什么我会在这里出现堆栈溢出?

c++ - 如何检查 free() 中的 diabolical wild free ?

C:二维 int 数组行的 free() 使程序停止

postgresql - 空闲的 postgres 进程占用大量内存

c++ - 优化最近邻大小调整算法以提高速度

C# XNA : Optimizing Collision Detection?