问题描述
任何编译器专家都可以对布尔值的有效使用发表评论吗?具体地说,编译器是否能够优化 std :: vector< boolean>
以使用最少的内存?有一个等效的数据结构吗?
Would any compiler experts be able to comment on the efficient use of boolean values? Specifically, is the compiler able to optimize a std::vector<boolean>
to use minimal memory? Is there an equivalent data structure that would?
过去,有些语言的编译器可以将布尔数组压缩为每个布尔值仅一位的表示形式.也许对于C ++而言,最好的方法是使用 std :: vector< char>
存储布尔值以最小化内存使用量?
Back in the day, there were languages that had compilers that could compress an array of booleans to a representation of just one bit per boolean value. Perhaps the best that could be done for C++ is to use std::vector<char>
to store the boolean values for minimal memory usage?
这里的用例将存储数亿个布尔值,其中一个字节可以节省很多空间,每个值超过4个或更多字节,甚至一个位甚至更多.
The use case here would be storing hundreds of millions of boolean values, where a single byte would save lots of space over 4 or more bytes per value and a single bit, even more.
推荐答案
std :: vector for bool是一种模板专门化功能,可以满足您的要求.
std::vector for bool is a template specialization that does what you are asking for.
您可以在此处了解更多信息.
You can read more here.
您可能还想探索标准的位集.
You may also want to explore the standard bitset.
这篇关于在C ++中有效使用布尔值true和false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!