我可以将向量的内容写成吗?直接从内部缓冲区到流?
我知道向量<布尔>是“邪恶的”,而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);
但结果不正确。我怀疑实施可能意味着这是一个愚蠢的尝试,但我不知道。
I know vector< bool > is "evil", and dynamic_bitset is preferred (bitset is not suitable) but I am using C++ Builder 6 and I don't really want to pursue the Boost route for such an old version. I tried :
int RecordLen = 1;
int NoBits = 8;
std::ofstream Binary( FileNameBinary );
vector< bool > CaseBits( NoBits, 0 );
Binary.write( ( const char * ) & CaseBits[ 0 ], RecordLen);
but the results are incorrect. I suspect that the implementation may mean this is a stupid thing to try, but I don't know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
vector
的 Operator[] 不返回引用(因为位不可寻址),因此获取返回值的地址将会充满问题。您是否考虑过 std::dequeOperator[] for
vector <bool>
doesn't return a reference (because bits are not addressable), so taking the return value's address is going to be fraught with problems. Have you consideredstd::deque <bool>
?bool 向量特化不会返回对 bool 的引用。
请参阅页面底部的此处。
the bool vector specialization does not return a reference to bool.
see here, bottom of the page.
对我来说,决定这有多合规已经为时已晚,但它对我有用:为位向量提供一个自定义分配器,以将这些位别名到您自己的缓冲区。
有人可以权衡向量内的反弹分配器是否需要从传入的分配器进行复制构造吗?适用于 GCC 4.2.1。我似乎记得该功能是 C++0x 所必需的,并且由于它与 C++03 中的任何内容都没有不兼容并且通常很有用,因此支持可能已经得到了广泛的支持。
当然,在
vector
使用的任何存储中,位是向前存储还是向后存储,还是左对齐还是右对齐,都是由实现定义的,因此请务必小心。It's too late for me to decide how compliant this is, but it works for me: give the bitvector a custom allocator to alias the bits to your own buffer.
Can someone weigh in with whether the rebound allocator inside the vector is required to be copy-constructed from the one passed in? Works on GCC 4.2.1. I seem to recall that the functionality is required for C++0x, and since it's not incompatible with anything in C++03 and is generally useful, support may already be widespread.
Of course, it's implementation-defined whether bits are stored forwards or backwards or left- or right-justified inside whatever storage
vector<bool>
uses, so take great care.