2

我正在研究 C++ 中的位图加载器,当从 C 样式数组移动到 std::vector 时,我遇到了一个 Google 似乎没有答案的常见问题。

8 位和 4 位位图包含一个调色板。调色板具有蓝色、绿色、红色和保留组件,每个组件的大小为 1 个字节。

// Colour palette     
struct BGRQuad
{
     UInt8 blue; 
     UInt8 green; 
     UInt8 red; 
     UInt8 reserved; 
};

我遇到的问题是,当我创建 BGRQuad 结构的向量时,我不能再使用 ifstream 读取函数将文件中的数据直接加载到 BGRQuad 向量中。

// This code throws an assert failure!
std::vector<BGRQuad> quads;
if (coloursUsed) // colour table available
{   // read in the colours
    quads.reserve(coloursUsed);
    inFile.read( reinterpret_cast<char*>(&quads[0]), coloursUsed * sizeof(BGRQuad) ); 
}

有谁知道如何直接读入向量而无需创建 C 数组并将数据复制到 BGRQuad 向量中?

4

1 回答 1

3

您需要使用quads.resize(coloursUsed). quads.reserve(coloursUsed)保留只是设置向量对象的容量,但不分配内存。调整大小实际上会分配内存。

于 2010-05-12T16:17:56.210 回答