我可以直接从内部缓冲区中将vector <bool>的内容写入流吗?</bool>

时间:2010-02-19 10:36:30

标签: c++ vector standards boolean

我知道矢量&lt; bool&gt;是“邪恶的”,并且dynamic_bitset是首选(bitset不适合),但我使用的是C ++ Builder 6,我真的不想为这样一个旧版本追求Boost路由。我试过了:

int RecordLen = 1;
int NoBits = 8;
std::ofstream Binary( FileNameBinary );
vector< bool > CaseBits( NoBits, 0 );
Binary.write( ( const char * ) & CaseBits[ 0 ], RecordLen);

但结果不正确。我怀疑实施可能意味着这是一个愚蠢的尝试,但我不知道

3 个答案:

答案 0 :(得分:1)

vector <bool>的运算符[]不返回引用(因为位不可寻址),因此获取返回值的地址将充满问题。您考虑过std::deque <bool>吗?

答案 1 :(得分:0)

bool vector specialization不会返回对bool的引用。

请参阅页面底部的here

答案 2 :(得分:0)

我决定这是多么顺从是为时已晚,但它对我有用:给bitvector一个自定义分配器,将这些位别名化为你自己的缓冲区。

有人可以权衡向量中的反弹分配器是否需要从传入的反射分配器进行复制构造?适用于GCC 4.2.1。我似乎记得C ++ 0x需要这个功能,并且因为它与C ++ 03中的任何东西都不兼容并且通常很有用,所以支持可能已经很普遍了。

当然,它的实现定义了位是在前面还是后面存储,或者在vector<bool>使用的存储内部左右对齐,所以要非常小心。

#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;

template< class T >
struct my_alloc : allocator<T> {
        template< class U > struct rebind {
                typedef my_alloc<U> other;
        };
        template< class U >
        my_alloc( my_alloc<U> const &o ) {
                buf = o.buf;
        }
        my_alloc( void *b ) { buf = b; }
         // noncompliant with C++03: no default constructor
        T *allocate( size_t, const void *hint=0 ) {
                return static_cast< T* >( buf );
        }
        void deallocate( T*, size_t ) { }
        void *buf;
};

int main() {
    unsigned long buf[ 2 ];
    vector<bool, my_alloc<bool> > blah( 128, false, my_alloc<bool>( buf ) );
    blah[3] = true;
    blah[100] = true;
    cerr << hex << setw(16) << buf[0] << " " << setw(16) << buf[1] << endl;
}
相关问题