C++ dynamic_bitset
发布网友
发布时间:2022-05-02 16:11
我来回答
共2个回答
热心网友
时间:2022-06-20 20:01
fout.write((char*)&bt, sizeof bt);
fin.read((char*)&rebt, sizeof bt);
又不是传统数据类型,输入输出的时候怎么会可以这样……
#include <iostream>
#include <fstream>
#include <boost/dynamic_bitset.hpp>
using namespace boost;
using namespace std;
int main()
{
int a=5;
int i;
dynamic_bitset<> bt(a);
for(i=0; i<a; i++)
{
cout<<bt[i]<<" ";
}
cout<<endl;
for(i=0; i<a; i++)
{
if(i%2==0)
{
bt.push_back(true);
}else
{
bt.push_back(false);
}
}
int len = bt.size();
cout<<"bt含有:"<<len<<" 个元素。";
cout<<endl;
//因为用的是动态分配,所以不能用sizeof去获取
//int capa = sizeof bt;
//cout<<"bt占用"<<capa<<"个字节。";
int capa = bt.num_blocks() * sizeof(dynamic_bitset<>::block_type);
cout<<"bt占用"<<capa<<"个字节。";
cout<<endl;
for(i=0; i<len; i++)
{
cout<<bt[i]<<" ";
}
cout<<endl;
ofstream fout("D:/dybit.dat", ios_base::out | ios_base::binary);
//取出原始数据,再写入文件
int nBlockCount = bt.num_blocks();
dynamic_bitset<>::block_type* blocks = new dynamic_bitset<>::block_type[nBlockCount];
to_block_range(bt, blocks);
fout.write((char*)blocks, nBlockCount * sizeof(*blocks));
delete[] blocks;
//关闭文件,免得打不开
fout.close();
ifstream fin("D:/dybit.dat", ios_base::in | ios_base::binary);
dynamic_bitset<> rebt(len);
//先读出原始数据,再恢复到对象
dynamic_bitset<>::block_type* newBlocks = new dynamic_bitset<>::block_type[nBlockCount];
fin.read((char*)newBlocks, nBlockCount * sizeof(*newBlocks));
fin.close();
from_block_range(newBlocks, newBlocks + nBlockCount, rebt);
delete[] newBlocks;
for(i=0; i<len; i++)
{
cout<<rebt[i]<<" ";
}
cout<<endl;
return 0;
}
来自:求助得到的回答
热心网友
时间:2022-06-20 20:02
什么意思 这么复杂!!