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

4 Comments »

  1. Another reason to use iterators is that the code you’ve posted relies on calling a function each time around the loop. For your sake, I hope your STL implementation is caching “size”, and not calculating it each time ;-).

    Comment by RichS — December 2, 2010 @ 4:49 pm

    • size() is a contant complexity method (by specification), so hopefully it just returns an internal counter and gets inlined, but it’s definitely worth pointing that out.

      Comment by rcomian — December 2, 2010 @ 4:55 pm

      • “size() is a contant complexity method (by specification),” – I may be incorrect, but according to my sources, this is not true.

        Comment by RichS — December 2, 2010 @ 5:01 pm

  2. Hi, I do think your blog may be having internet browser compatibility problems.

    When I look at your web site in Safari, it looks fine however, when opening in Internet Explorer, it’s got some overlapping issues. I just wanted to give you a quick heads up! Besides that, fantastic website!

    Comment by uk vps hosting — August 5, 2013 @ 11:32 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: