menaci342
menaci342

Reputation: 151

Is it okay to access vector elements with an integer index?

I have some integer variables and a vector. I need to use the integer variable as a index in the vector.

Is it okay to simply say some_vector[some_integer]?

Or do I need to somehow convert the integer to a size type?

Upvotes: 4

Views: 1189

Answers (1)

aparpara
aparpara

Reputation: 2201

Yes, is will be converted to size_t without any warnings or errors. But beware of negative values. If your int i is negative, the conversion will yield std::numeric_limits<size_t>::max() + 1 - abs(i), usually a very large number which is likely to lead to undesirable consequences. So if the index can be negative, check it before the indexing.

UPD: Strictly speaking, there may be a warning depending on your compiler flags. In case of g++ there are two of them relevant here:

  1. -Wconversion warns about conversions that may alter the value. In integer conversions this may occur when the destination type is smaller than the source (e.g. int32_t y = 1000; int16_t x = y;).
  2. Signed-unsigned conversions where the destination is unsigned (e.g. int16_t y = -1; uint32_t x = y;) or the destination is of the same size as the source (e.g. unsigned int y = UINT_MAX; int x = y;) may change the value too, and in C -Wconversion does issue the warning, but in C++ you need to add -Wsign-conversion to make it appear.

I suspect they made the distinction in C++ precisely because people usually index std::vector using int and would have to make too much static_casts to get rid of the warning if it appeared in this case.

Microsoft CL covers the first case by warning C4244, turned on by /W3 or /W4, and for the second case I could'n find a warning switch. If someone knows, please tell in a comment.

AFAIK, the C++ standard doesn't explicitly require size_t to be of equal size or larger than int. But I don't know any platform where it is not the case. So conversion from int to size_t falls into the second category.

To summarize: most likely, you will not receive a warning for int to size_t conversion in C++, as I stated before, unless you are using g++ with -Wsign-conversion switch.

Upvotes: 6

Related Questions