2

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::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?

Thomas
  • 174,939
  • 50
  • 355
  • 478
Sent1nel
  • 509
  • 1
  • 7
  • 21
  • Do not try to use HTML tags to format your code. Just select the code and hit the 1010 button above the text entry area. Also, post the code from your IDE/editor using copy & paste - what you have posted is obviously not the real code. –  May 12 '10 at 16:16
  • @Thomas Please do not correct code in questions - it's imperative that the code remains what the OP posted. If you want to point out it is not correct, leave a comment. –  May 12 '10 at 16:19
  • Possible dupe of http://stackoverflow.com/questions/2780365/using-read-directly-into-a-c-stdvector/2780539#2780539 – KillianDS May 12 '10 at 16:20
  • @Neil: Normally I wouldn't. But this was so obviously a typo that I figured it didn't matter. – Thomas May 12 '10 at 16:23
  • Thanks for the tip Neil I didn't even notice the "1010" button. I'll certainly use it in future. – Sent1nel May 12 '10 at 16:31

1 Answers1

3

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.

Jason B
  • 12,835
  • 2
  • 41
  • 43