c++ - 如何设置整数的最小/最大值,其中 `++` 和 `--` 以及一般数学服从您在 c++ 中设置的限制?

标签 c++ integer operator-overloading integer-overflow

我不想在代码中乱扔一堆 if 语句,我想知道一个干净的方法来设置一个整数的限制,当遍历这些限制时它仍然会包装它的值。

例如,

int i(9998);
setMinMax(i,-27315, 10000); // Absolute Zero - Boiling Point of water
i++; // ==  9999
i++; // ==  10000
i++; // == -27315

如果最小-最大值可以是动态的,那将是理想的。我不介意创建新类型或运算符重载。我只是想避免做这样的事情:

int i = foo();
int j = bar();
int min(-27315);
int max(10000);
i += j;
     if (i==min-1) {i=max}
else if (i==max+1) {i=min}
else if (i>max) {i=min+(i-max)}
// more stupid code

谢谢。

最佳答案

这可以完成,但不能使用原始 int。你需要实现你自己的类类型来重载各种算术运算符,以便看起来和感觉起来就像一个 int。这是实现此目的的一种方法:

#include <limits> // for numeric_limits

struct RangedInt {
private:
    int m_min = std::numeric_limits<int>::min();
    int m_max = std::numeric_limits<int>::max();
    int m_val = 0;
public:
    RangedInt(int value = 0) : m_val(value) {}

    void setMinMax(int min, int max){
        m_min = min;
        m_max = max;
        m_val = std::min(std::max(m_val, m_min), m_max);
    }

    // pre-increment
    RangedInt& operator++(){
        m_val++;
        if (m_val > m_max) m_val = m_min;
        return *this;
    }

    // post-increment
    RangedInt operator++(int){
        RangedInt tmp {*this}; // create temporary with old value
        operator++(); // perform increment
        return tmp; // return temporary
    }

    // pre-decrement
    RangedInt& operator--(){
        m_val--;
        if (m_val < m_min) m_val = m_max;
        return *this;
    }

    // post-decrement
    RangedInt operator--(int){
        RangedInt tmp {*this}; // create temporary with old value
        operator--(); // perform decrement
        return tmp; // return temporary
    }

    // this can be extended to implement the following operators
    RangedInt operator+(const RangedInt& x);
    RangedInt operator+(int x);
    RangedInt operator-(const RangedInt& x);
    RangedInt operator-(int x);
    RangedInt& operator+=(const RangedInt& x);
    RangedInt& operator+=(int x);
    RangedInt& operator-=(const RangedInt& x);
    RangedInt& operator-=(int x);
    // and lots more, for *, /, unary +/-, etc...

    // convenient conversion to int:
    explicit operator int(){
        return m_val;
    }
};

上面的代码现在可以让您编写以下内容:

RangedInt i = 9998;
i.setMinMax(-27135, 10000);
std::cout << (int)i << '\n'; // 9998
i++;
std::cout << (int)i << '\n'; // 9999
i++;
std::cout << (int)i << '\n'; // 10000
i++;
std::cout << (int)i << '\n'; // -27135

可以使用模板扩展此方法以适用于任何数字类型,而不仅仅是 int,并且您还可以将最小值和最大值转换为模板参数,如果它们在编译时已知的话内存占用是一个问题。

关于c++ - 如何设置整数的最小/最大值,其中 `++` 和 `--` 以及一般数学服从您在 c++ 中设置的限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53679812/

相关文章:

c++ - 为什么代码不能返回正确的值?

c++ - 意外异常

c++ - 计算整数中的位数(负整数?)

linux - 如何在汇编循环中打印整数

c++ - 运算符重载 - 创建一个新的 String 类

c++ - 带有 Boost 的 CMake 找不到静态库

删除未使用的变量后 C++ hangUp

c++ - 显示非常大的数字,由 byte[] 表示

c++ - 不使用模板重载乘法运算符

r - 重载下标运算符 "["