Sign in to follow this  
thallish

Difference between .resize() and .reserve()

Recommended Posts

thallish    202
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
rip-off    10976
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this