C 中STD :: vector的压实bool功能

Compacting bools feature of std::vector in C++

本文关键字:bool 功能 vector STD      更新时间:2023-10-16

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