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

后端 未结 2 524
萌比男神i
萌比男神i 2021-01-18 08:41

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

2条回答
  •  长情又很酷
    2021-01-18 09:06

    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.

提交回复
热议问题