tips for subscript operator

本文通过《C++ Primer》中的一段话强调了C++内置数组与标准库类型如vector和string在使用下标操作符时的区别。对于内置数组而言,下标可以接受负数,而vector和string则强制要求下标为非负数。

Quote from the << C++ prime>>:

"""

int *p = &ia[2]; // ia[] is a int-type array, it contains  5 elements.

int j = p[1];

int k = p[-2];

This last example points out an imiportant difference between arrays and library types such as vector and string that have subscript operators. The library types force the index used with a subscript to be an unsigned value. The built-in subscript operator does not. The index used with the built-in subscript operator can be a negative value. Of course, the resulting address must point to an element in (or one past the end of ) the array to which the original pointer points.

"""

The paragraph stress the difference of subscript-operator for different types.. the index used with the built-in subscript operator can't be a negative value for vector and string.

Warning:

Unlike subscripts for vector and string, the index of the built-in subscript operator is not an unsigned type.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值