Jump to content
  • Advertisement
Sign in to follow this  
thallish

Difference between .resize() and .reserve()

This topic is 4212 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Ahh so if I am trying to access the first element when using reserve, then it complains because there is no element yet?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!