Reputation: 309
This might sound crazy but I'm working with floor numbers of a building which has -0 as floor and -0A, B, and C so and so.
My user in entering floor data randomly. In the end I'm supposed to sort the array of these floor numbers. What i found is that even if i enter -0 as floor number and try to sort it.. it sorts it as 0 because for computer -0 is still 0.
How do i define -0 and -1<-0<0?
Upvotes: 0
Views: 138
Reputation: 53000
All answers so far are suggesting your own type/functions and probably strings.
Strings will work but you can take an idea from floating-point and store them as sign (boolean or even bit flag) and magnitude (unsigned integer type, 8 or 16 bits should be sufficient).
Comparison is simply compare signs and then compare magnitudes if required.
You could use a struct
for such a type which would give you the same value semantics as integer and real types and avoid object allocation.
If there is also a letter ("-0 as floor and -0A, B, and C so and so") that can be a third field in the struct, probably a char
, and you could still have value semantics.
HTH
Upvotes: 1
Reputation: 162712
By definition, you are no longer working with integers as -0 != 0
makes no sense in the realm of integers.
So, yes, you're going to have to define your own type and implement your own sorting rules. Simply storing them as strings and then implementing a sorting block to sort an array of them is straightforward, though.
You could go down the path of using floats so you could have floor 0 and floor -0.1, then round for display. But that sort of shenanigans will lead the maintainer after the maintainer after you to call you unpleasant names (which is sometimes OK). :)
Upvotes: 2