Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set an integer's interval?

Tags:

c++

integer

range

I know this is a very noob-ish question,but how do I define an integer's interval?

If I want an integer X to be 56<= X <=1234 , how do I declare X ?


1 Answers

The best way would be to create your own integer class with bounds on it and overloaded operators like +, * and == basically all the ops a normal integer can have. You will have to decide the behavior when the number gets too high or too low, I'll give you a start on the class.

struct mynum {
    int value;
    static const int upper = 100000;
    static const int lower = -100000;
    operator int() {
        return value;
    }
    explicit mynum(int v) {
        value=v;
        if (value > upper)value=upper;
        if (value < lower)value=lower;
    } 
};
mynum operator +(const mynum & first, const mynum & second) {
   return mynum(first.value + second.value);
}  

There is a question on stackoverflow already like your question. It has a more complete version of what I was doing, it may be a little hard to digest for a beginner but it seems to be exactly what you want.

like image 62
aaronman Avatar answered Dec 17 '25 09:12

aaronman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!