开发者

Using std::ifstream to load in an array of struct data type into a std::vector

I am working on a bitmap loader in C++ and when moving from the C style array to the std::vector I have run into an usual problem of which Google does not seem to have the answer.

8 Bit and 4 bit, bitmaps contain a colour palette. The colour palette has blue, green, red and reserved components each 1 byte in size.

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

The problem I am having is when I create a vector of the BGRQuad structure I can no longer use the ifstream read function to load data from the file directly into the BGRQuad vector.

// This code throws an assert failure!
std开发者_如何学Go::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) ); 
}

Does anyone know how to read directly into the vector without having to create a C array and copy data into the BGRQuad vector?


You need to use quads.resize(coloursUsed) in place of quads.reserve(coloursUsed). Reserve just sets the capacity of the vector object but does not allocate memory. Resize will actually allocate the memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜