Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do random access iterator's arithmetic operators accept / return int and not size_t?

Tags:

c++

iterator

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 fix some signed / unsigned conversion issues that I know I have, and this message surprised me:

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

It was generated by this code:

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

I've got a lot of other similar messages suggesting that iterator's arithmetic operators accept and return int. Why not size_t? Fixing all these messages is a pain, and doesn't make my code prettier!

like image 638
Violet Giraffe Avatar asked Mar 21 '14 12:03

Violet Giraffe


2 Answers

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.

like image 119
Mike Seymour Avatar answered Sep 17 '22 21:09

Mike Seymour


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.

like image 30
jrok Avatar answered Sep 21 '22 21:09

jrok