C++进阶⑤:运算符优先级、四种强制类型转换、accumulate、bit_xor()、string.size()返回无符号整数、int和unsigned的转换

1 运算符优先级

运算符优先级

初等运算符->单目运算符->算数运算符->关系运算符->逻辑运算符->条件运算符->赋值运算符->逗号运算符;

2 四种强制类型转换

四种强制类型转换
static_cast<>() / dynamic_cast<>() / const_cast<>() / reinterpret_cast

3 accumulate

int sum = accumulate(vec.begin() , vec.end() , 42);
string sum = accumulate(v.begin() , v.end() , string(" "));  

accumulate带有三个形参:头两个形参指定要累加的元素范围,第三个形参则是累加的初值。
accumulate函数将它的一个内部变量设置为指定的初始值,然后在此初值上累加输入范围内所有元素的值。accumulate算法返回累加的结果,其返回类型就是其第三个实参的类型。

4 bit_xor()

bit_xor()
异或的函数对象类。
可用作 transform 或者 accumulate等的操作符。
类似的还有与操作bit_and 、或操作 bit_or。
#include < functional >

5 string.size()函数的返回值是无符号类型整数。

C++中string类size() length()函数的返回值是无符号类型整数,unsigned int。
①不能直接用max/min函数比较int类型和size()返回值

int a = 0;
string word = "abc";
a = max(a, word); /error,word是unsigned int类型,不能与int类型比较。

②当int和unsigned int类型比较时,会默认把int类型转换为unsigned,如果int型变量是负数,会出现错误。

int a = -1;
string word = "abc";
while (a < word.size()) {
...} /error,把int类型的-1转换为unsigned类型会变成4294967295,永远无法进入循环

负数在计算机中存的是它的补码,对于-1:
原码是 1000 0000 0000 0000 0000 0000 0000 0001
补码 是 1111 1111 1111 1111 1111 1111 1111 1111 ,即0xFFFFFFFF
-1转换成unsigned无符号的时候,会直接赋值给unsigneed
所以-1转换后变成1111 1111 1111 1111 1111 1111 1111 1111,即0xFFFFFFFF,即2^32 - 1
2^32 = 4294967296
在这里插入图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值