Since most operations on std::vector
require / return size_t
- that\'s the type I use for indexing. But now I\'ve enabled all compiler warnings to
I've got a lot of other similar messages suggesting that iterator's arithmetic operators accept and return
int
.
Not necessarily int
. It's the (signed) difference_type
defined by the iterator type's iterator_traits
. For most iterator types, this defaults to ptrdiff_t
.
Why not
size_t
?
Because arithmetic needs to work correctly with signed values; one would expect it + (-1)
to be equivalent to it - 1
.
It allows for things like it += index;
where index
can be both positive or negative (according to some logic).
Comparing with the following:
if (some_condition)
it += index;
else
it -= index;
Which would be needed if we could only pass unsigned values.