c++ - 如何有效地循环连续数字c++

标签 c++ performance

我正在寻找一种基于输入值循环遍历连续数字的解决方案。类似于模数,但对于负数不同。与下面低效的代码相比,是否有更好的解决方案?以下是一些输入/输出示例:

Numbers range 0 to 2
-2 -> 1
-1 -> 2
 0 -> 0
 1 -> 1
 2 -> 2
 3 -> 0
 4 -> 1

//Inefficient Code example
int getConsecutiveVal(int min, int max, int input) //Inclusive in this scenario
{
    while (input>max)
        input -= (1+max-min);
    while (input<min)
        input += (1+max-min);
    return input;
}

//Incorrect Code example since func(0,2,-1) returns 2
int getConsecutiveVal(int min, int max, int input)
{
    return (input % (1+max-min))+min;
}

最佳答案

为了能够递增递减,我使用了以下函数。它不止 1 行,但数学运算更少。它在精神上与原始海报的格式相似。测试了阳性和阴性病例。

int16_t cycleIncDec(int16_t x, int16_t dir, int16_t xmin, int16_t xmax) {
    // inc/dec with constrained range
    // the supplied xmax must be greater than xmin
    x += dir;
    if      (x > xmax) x = xmin;
    else if (x < xmin) x = xmax;
    return x;
}

具有各种起始值和步长的 cycleIncDec() 输出

x:  11: +1      0    1    2    3    4    5    6    0    1    2    3
x:   4: -1      3    2    1    0   -1   -2   -3   -4   -5   -6   -7
x:  -8: -1    -13  -12  -11  -10   -9   -8  -13  -12  -11  -10   -9
x:-190: -2   -192 -194 -196 -198 -200 -170 -172 -174 -176 -178 -180

关于c++ - 如何有效地循环连续数字c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27615050/

相关文章:

c++ - 如何为算术表达式创建 BST

c++ - 编码加号问题(执行 Poco::URI::setQueryParameters 和 Poco::URI::getQueryParameters 给出意外结果)

c++ - 作为构造函数参数的构造函数调用将声明评估为函数指针

c++ - c++ 模板会使程序变慢吗?

mysql - 如何消除mysql查询中的重复记录

java - JMH 基准测试避免 jvm 优化

c++ - 在命名空间中定义一个类

sql-server - 开发直接访问 SQL 服务器的桌面应用程序是不是一个坏主意?

postgresql - Postgres : forcing analyzer to use bitmap scan instead of index scan

c++ - 如何从 C++ 中删除的对象中清除内存?