我正在处理一个将使用 bitset 的项目。由于提供的文本文件非常大(>800M),将其直接加载到 std::bitset 将花费超过 25 秒。所以我想将文本文件预处理为内存转储的二进制文件。因为 8 位 char 会转换为 1 位,所以文件加载的成本时间会大大减少。我写了一个演示代码:
#include <iostream>
#include <bitset>
#include <string>
#include <stdexcept>
#include <fstream>
#include <math.h>
int main () {
const int MAX_SIZE = 19;
try {
std::string line = "1001111010011101011";
int copy_bypes = (int)ceil((float)MAX_SIZE / 8.0);
std::bitset<MAX_SIZE>* foo = new (std::nothrow)std::bitset<MAX_SIZE>(line); // foo: 0000
std::ofstream os ("data.dat", std::ios::binary);
os.write((const char*)&foo, copy_bypes);
os.close();
std::bitset<MAX_SIZE>* foo2 = new (std::nothrow)std::bitset<MAX_SIZE>();
std::ifstream input("data.dat",std::ios::binary);
input.read((char*)&foo2, copy_bypes);
input.close();
for (int i = foo2->size() -1 ; i >=0 ; --i) {
std::cout << (*foo2)[i];
}
std::cout <<std::endl;
}
catch (const std::invalid_argument& ia) {
std::cerr << "Invalid argument: " << ia.what() << '\n';
}
return 0;
}
看起来工作正常,但我担心这种用法在生产环境中真的可以正常工作。
感谢一些先进的。