是否有任何编译器专家能够评论 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/