# 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);


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 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 on other sites
thallish    202
Ahh so if I am trying to access the first element when using reserve, then it complains because there is no element yet?

##### Share on other sites
rip-off    10976
Quote:
 Original post by thallishAhh so if I am trying to access the first element when using reserve, then it complains because there is no element yet?

Exactly.

thallish    202
thank you [wink]