C++ 拾遗

发布时间 2024-01-02 21:32:57作者: klaycsu

leetcode内存超时

在做leetcode时,使用了字符串拼接,导致内存爆掉。

//res = res + curr+to_string(count);//超出内存限制
 res += curr+to_string(count);  //这样才能通过

res = res + string的时候会开辟新的内存存放res+s,字符串太长,开辟新空间就需要消耗大量内存,所以导致内存超了。
res += string的话相当于res.append(string),直接在字符串末尾添加字符.

0 < -2的问题

string S1 = "1234";
string S2 = "1234";

if(S2.size() - S1.size() < -2)
{
    cout << "S2.size() - S1.size():"<< S2.size() -  S1.size() <<" < " << -2 ;
}

[output]: S2.size() - S1.size():0 < -2

很奇怪,是不是,于是debug了一下

(gdb) ptype(S1.size())
type = unsigned long long

可以看出S1.size()是无符号的long long类型
在于负数做比较是 -2 首先转换成无符号的long long 类型,也就是18446744073709551614
可以是大于0的了。

unsigned long long ull1 = 1;
unsigned long long ull2 = 2;
cout << ull1 - ull2;

[output]:18446744073709551615

也输出也不是-1 ,而是转换成了默认的unsigned long long。