Reputation: 13487
I have a problem that is quite common in the code that I am writing at the moment whereby I want to have an integer that can only exist inside a certain range where the range is [start, end). Basically I want to be able to do something like the following:
cyclic_int ci(4, 8);
ci = 4;
assert(ci == 4);
ci += 3;
assert(ci == 7);
ci += 2;
assert(ci == 5);
assert(ci == 13);
And that should all return true. Basically the class automatically applies modulus (%) for me and the integer acts as a cyclic integer in the range that I init it with. I could implement this class myself and overload all of the common operators to make it work nicely with normal integers but it seems like a useful class that somebody may have made before.
So my question is this, is there a common class like this out there somewhere that everyone uses or am I thinking of doing it the wrong way and is there a better simpler way. (My aim is to not have to constantly think about applying the % operator or any similar function over it) Thanks.
Edit: I decided to write my own one as well just for fun: http://github.com/robertmassaioli/wrapping_number
Upvotes: 10
Views: 648
Reputation: 14148
I never used it and it is not yet an official Boost library, but Boost.ConstrainedValue has a wrapping_int
that looks very similar to what you're looking for.
Although it is not yet a part of Boost, it was reviewed and, IIUC, conditionally accepted recently: http://lists.boost.org/boost-announce/2010/09/0265.php
The library is available at http://rk.dl.pl/f/constrained_value.zip
The documentation is at http://rk.dl.pl/r/constrained_value
Upvotes: 2
Reputation: 272657
These may not be exactly what you want, but you may be interested in one of the many Galois-field libraries out there (http://www.google.co.uk/search?q=galois+field+c%2B%2B+library). I've never used any of them, so I can't give a specific recommendation.
Upvotes: 1
Reputation: 26995
Is not it easier to use the function normalize
?
int normalize(int val, int start, int end)
{
return (val - start) % (end - start) + start;
}
int ci = 4;
assert(ci == 4);
ci = normalize(ci + 3, 4, 8);
assert(ci == 7);
ci = normalize(ci + 2, 4, 8);
assert(ci == 5);
assert(ci == 13);
Upvotes: 4