为什么随机访问迭代器的算术运算符接受/返回int而不是size_t? [英] Why do random access iterator's arithmetic operators accept / return int and not size_t?

查看:111
本文介绍了为什么随机访问迭代器的算术运算符接受/返回int而不是size_t?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为 std :: vector 上的大多数操作都需要/ return size_t - 这是我用于索引的类型。但现在我已经启用所有的编译器警告,修复一些签名/未签名的转换问题,我知道我有,这个消息让我惊讶:

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':从'size_t'转换为'__w64 int',签名/未签名不匹配

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

此代码:

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

我有很多其他类似的消息,建议迭代器的算术运算符接受并返回 int 。为什么 size_t ?修复所有这些消息是一种痛苦,并且不会使我的代码更漂亮!

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!

推荐答案


有很多其他类似的消息,表明迭代器的算术运算符接受并返回 int

不一定 int 。它是由迭代器类型的 iterator_traits 定义的(signed) difference_type 。对于大多数迭代器类型,默认为 ptrdiff_t

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.


$ c> size_t ?

因为算术需要使用带符号值正确工作;人们会期望 it +(-1)等同于 it-1

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

这篇关于为什么随机访问迭代器的算术运算符接受/返回int而不是size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆