开发者

Compare result of std::distance with an unsigned type

I wish to compare index of an element in a std::vector to an unsigned value. If I directly compare like;

if(std::distance(...)>min_di开发者_如何学运维stance) // true for some

I just get a warning, but works fine. However, to get rid of the warning, if I cast min_distance to int, I do not get any comparison result (although there is)

if(std::distance(...)>(int)min_distance) // never true

What is the exact problem?


Try:

if ( std::abs( std::distance( ... ) ) > min_distance )

std::distance returns a signed value. I am assuming you are trying to get the distance in such a way that -2 AND 2 would be considered as 2. The abs function gives you the absolute value which means that whatever the sign of the input, you always get a positive value back.


It sounds like distance is returning a negative number in some cases. Normally it would cast the int up to unsigned and the negative number would become large enough to be greater than your condition.

In the second case you would be comparing a negative number against the small positive number cast to int.

You can test this out by printing the result from distance immediately prior to using it in the comparison.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜