Difference between .resize() and .reserve()

Started by
3 comments, last by thallish 17 years, 5 months ago
Hi I am having some trouble understanding the difference between the two aforementioned methods. I am reading some data from a file and placing them in a std::vector:

std::vector<unsigned char> in;
	
// resize space for number of vertices 

//in.reserve(numVertices); // using reserve does not work
in.resize(numVertices); // using resize does

// filter the heights
bool filter = true;

// open heightmap file
inFile.open(heightmapFile.c_str(), std::ios_base::binary );
if(!inFile) HR(E_FAIL);
		
// Read the RAW bytes.
inFile.read((char*)&in[0], (std::streamsize)in.size());

The problem occurs when I in the last line when reading from the file. "Vector subscript out of range" is the error and that means that I am trying to access some memory that I shouldn't, but why is that only when I am using reserve()? Does reserve manipulate some internal iterator and that way screw up my access operator? regards
regards/thallishI don't care if I'm known, I'd rather people know me
Advertisement
Resize creates or destroys elements such that there are the specified number in the vector.

If you reserve space for length() + 100 elements, then you can push_back ( or otherwise add ) 100 more elements without triggering any more reallocations by the vector.

Basically, reserve changes the vectors capacity, while resize changes the vectors size.
Ahh so if I am trying to access the first element when using reserve, then it complains because there is no element yet?

regards/thallishI don't care if I'm known, I'd rather people know me
Quote:Original post by thallish
Ahh so if I am trying to access the first element when using reserve, then it complains because there is no element yet?


Exactly.
thank you [wink]
regards/thallishI don't care if I'm known, I'd rather people know me

This topic is closed to new replies.

Advertisement