C 中STD :: vector的压实bool功能
Compacting bools feature of std::vector in C++
c 紧凑型布尔中的std ::向量是否吗?我的意思是我已经读到STD :: vector可以将8个布尔值组合为1个字节。但是,当我在Visual Studio中尝试此代码时,
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<bool> array {true, false, false, true, true,false,false,true};
cout << sizeof(array) << endl;
cout << sizeof(array[0]) << endl;
getchar();
return 0;
}
它打印:
24
16
在另一个IDE(例如CodeBlocks(中,它打印了20和8。
我在这里不太了解布尔值。
c 紧凑型布尔中的std ::向量是否?
是的,允许这样做,通常这样做。
我在这里不太了解布尔值。
您实际上没有得到array[0]
评估的内容。
它不评估 bit 。它评估了正确处理转换为bool
的代理对象和bool
的分配。
sizeof
此代理没有太大的意义。它的大小不像一点或布尔。它是对特定位作用的对象的大小。
std::vector
通常在内部使用动态分配。如果您定义了跟踪实际分配大小的分配器,您会发现为vector<bool>
分配的字节数意味着值存储为位:
#include <vector>
#include <iostream>
template<typename T>
class my_allocator : public std::allocator<T> {
public:
T * allocate(const size_t count) {
std::cout << "Allocated " << count << " * " << typeid(T).name() << std::endl;
std::cout << "Total size: " << count * sizeof(T) << std::endl;
return std::allocator<T>::allocate(count);
}
T * allocate(const size_t count, const void *) {
return allocate(count);
}
template<typename U>
struct rebind {
typedef my_allocator<U> other;
};
my_allocator() noexcept {};
my_allocator(const my_allocator<T>&) noexcept = default;
template<typename Other>
my_allocator(const my_allocator<Other>&) noexcept {}
};
int main() {
std::vector<int, my_allocator<int>> v1 { 0 };
std::vector<bool, my_allocator<bool>> v2 { 0 };
v1.reserve(100);
v2.reserve(100);
return 0;
}
相关输出:
Allocated 100 * int
Total size: 400
Allocated 4 * unsigned int
Total size: 16
演示:https://wandbox.org/permlink/whtd0k3smvd3e4ag
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 写入向量<向量<bool>>
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- C 中STD :: vector的压实bool功能
- 在使用C 中使用多个三元运算符时,BOOL和ENUM类型超载的功能没有区分
- 功能模板专业化中的bool返回值
- 在C 中返回bool的功能