1

我正在处理一个将使用 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;
}

看起来工作正常,但我担心这种用法在生产环境中真的可以正常工作。

感谢一些先进的。

4

2 回答 2

0

将二进制非平凡类写入文件非常危险。您应该将 bitset 转换为明确定义的二进制数据。如果您知道您的数据适合 unsigned long long,您可以使用 bitset<>::to_ullong() 并写入/读取该 unsigned long long。如果您希望这是跨平台的 beetwet,例如 64 位和 32 位平台,您应该使用固定大小的类型。

于 2016-07-19T09:04:42.560 回答
0

这两行是错误的

os.write((const char*)&foo, copy_bypes);
input.read((char*)&foo2, copy_bypes);

您将指针的地址传递给foo2,而不是std::bitset对象本身。但即使它被纠正:

os.write((const char*)foo, copy_bypes);
input.read((char*)foo2, copy_bypes);

在生产环境中使用是不安全的。在这里,您假设这std::bitset是一个PODtype并按此方式访问它。但是,当您的代码变得更加复杂时,您就有编写或阅读过多的风险,并且没有任何安全措施可以阻止未定义行为的发生。std::bitset被做得很方便,而不是快速,它通过它提供的访问位的方法来表达——没有适当的方法来获取它的存储地址,例如,std::vector或者std::string提供。如果您需要性能,则需要自己实现。

于 2016-07-19T09:52:27.077 回答