Developer Drain Brain

December 2, 2010

std::vector indexes have a type – and it’s not “int”

Filed under: Development — Tags: , — rcomian @ 12:51 pm

Just a quick aside, I’ve seen a fair bit of code recently of this kind:

std::vector<int> myvector = …
for (int i = 0; i < myvector.size(); ++i)

This code produces a warning when compiled, and it’s right to do so.

Vectors are awkward beasts – this means that they fit in with the rest of c++. In particular, the type of the variable “i” above, is not an int, unsigned int or a dword, it’s std::vector<int>::size_type.

This size type is also the numeric value accepted by the [] operator. Int will pass into this operator without warning, but it’s not correct. And going the other way – especially via myvector.size(), is a potential issue.

So the for loop above should be written:
std::vector<int> myvector = …
for (std::vector<int>::size_type i = 0; i < myvector.size(); ++i)

Or, even better, use iterators!

See also:
http://www.cplusplus.com/reference/stl/vector/

Advertisements

Blog at WordPress.com.