tags:

views:

43

answers:

2

Hi, 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_distance) // 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?

A: 

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 "absoloute" value which means that whatever the sign of "n" you always get a positive value back.

Goz
actually, I am sure that distance will return >=0 in my case, since I compare with the beginning and sure that the element is inside. my question is a more general casting problem actually.
paul simmons
Whats the value of min_distance then? Surely it is greater than 0? What compiler are you using? I can't see why casting to an "int" would cause a problem ... unless min_distance is greater than 2^31 ..
Goz
sth. less than 10, btw i'm using g++
paul simmons
Alas I don't have G++ to hand but a quick test compiled perfectly under VS2010 :(
Goz
probably `distance()` in your case is returning negative value. debug it properly to have the root cause.
Donotalo
argh! my mistake, calling distance as distance(iterator,begin), instead of (begin,iterator) which was giving negative
paul simmons
A: 

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.

Mark B