Why do random access arithmetic operators accept and return int rather than size_t?

Since most operations on std::vector require / return size_t - the type that I use for indexing. But now I have included all the compiler warnings to fix some problems with the signed / unsigned conversion that I know I have, and this message surprised me:

warning C4365: 'argument': conversion from 'size_t' to '__w64 int', signature mismatch / unsigned

It was generated by this code:

 std::vector<int> v; size_t idx = 0; v.insert(v.begin() + idx + 1, 0); 

I have many other similar posts suggesting that iterator arithmetic operators accept and return int . Why not size_t ? Correcting all of these messages is pain and does not make my code more beautiful!

+6
source share
2 answers

I have many other similar posts suggesting that iterator arithmetic operators accept and return int .

Not necessarily int . This is the (signed) difference_type defined by the iterator_traits iterator_traits type. For most types of iterators, this default value is ptrdiff_t .

Why not size_t ?

Since arithmetic should work correctly with signed values; one would expect that it + (-1) would be equivalent to it - 1 .

+7
source

It allows things like it += index; , where index can be either positive or negative (according to some logic).

Comparison with the following:

 if (some_condition) it += index; else it -= index; 

This would be necessary if we could only pass unsigned values.

+2
source

All Articles