[英]Why do random access iterator's arithmetic operators accept / return int and not size_t?
Since most operations on std::vector
require / return size_t
- that's the type I use for indexing. 由于
std::vector
上的大多数操作都需要/ return size_t
- 这是我用于索引的类型。 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
警告C4365:'参数':从'size_t'转换为'__w64 int',有符号/无符号不匹配
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
. 我有很多其他类似的消息表明迭代器的算术运算符接受并返回
int
。 Why not size_t
? 为什么不
size_t
? Fixing all these messages is a pain, and doesn't make my code prettier! 修复所有这些消息是一件痛苦的事,并不能使我的代码更漂亮!
I've got a lot of other similar messages suggesting that iterator's arithmetic operators accept and return
int
.我有很多其他类似的消息表明迭代器的算术运算符接受并返回
int
。
Not necessarily int
. 不一定是
int
。 It's the (signed) difference_type
defined by the iterator type's iterator_traits
. 它是迭代器类型的
iterator_traits
定义的(带符号) difference_type
。 For most iterator types, this defaults to ptrdiff_t
. 对于大多数迭代器类型,默认为
ptrdiff_t
。
Why not
size_t
?为什么不
size_t
?
Because arithmetic needs to work correctly with signed values; 因为算术需要与有符号值一起正常工作; one would expect
it + (-1)
to be equivalent to it - 1
. 人们会期望
it + (-1)
等于it - 1
。
It allows for things like it += index;
它允许像它这样的东西
it += index;
where index
can be both positive or negative (according to some logic). 其中
index
可以是正数也可以是负数(根据某些逻辑)。
Comparing with the following: 与以下比较:
if (some_condition)
it += index;
else
it -= index;
Which would be needed if we could only pass unsigned values. 如果我们只能传递无符号值,那将是必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.