问题描述
最近我在尝试用 C++ 减去两个字符串的 .size()
值时遇到了一个问题.据我所知, size()
返回字符串中的字符数.所以假设我有 2 个字符串 p
和 q
,abs(p.size()-q.size())
应该返回我的差异两个字符串的长度.但是当我运行这段代码时,它突然返回了一个很大的值.当我单独打印两者的长度或者如果我将它们的长度值存储在不同的整数中并减去它们时,它们会给我正确的答案.我还没有弄清楚原因.
Recently I encountered a problem while I was trying to subtract .size()
values of two strings in c++. As far as I know, size()
returns number of characters in a string. So lets say I have 2 strings p
and q
, abs(p.size()-q.size())
should return me difference in length of both strings. But when I ran this code, it returned an abruptly large value. When I individually print the length of both or if I store their length values in different integers and subtract them, they give me correct answer. Am not yet able to figure out why.
推荐答案
size()
返回一个无符号值.较小的无符号值减去较大的值会下溢计算,从而产生较大的负值.把它想象成汽车里有里程或公里的滚动"计数器,当你回滚到 0 时,它变成了 99999,这是一个很大的数字.
size()
returns an unsigned value. A smaller unsigned value minus a larger one is then underflowing the calculation, resulting in a large negative value. Think of it as if you have the "rolling" counter of miles or km in a car, and you roll back past 0, it becomes 99999, which is a big number.
假设您关心负差异,解决方案是执行 static_cast(p.size() - q.size())
(并将其传递给 abs代码>).
The solution, assuming you care about negative differences is to do static_cast<int>(p.size() - q.size())
(and pass that to abs
).
这篇关于减去不同字符串的 .size() 函数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!