Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我不确定如何获得反向索引,index%size 可以使用直环索引,但我需要的是,如果你在 0 索引中,则将最后一个索引作为 0 的前一个索引。
[0][1][2][3] // the previous index of 0 should be 3
在语言C中,余数运算符可用于如下获得真(正)模结果:
(index+n-1)%n
其中n是数组的长度。
如果我理解正确,那么您可以只说prev(index) = (index-1) % len(array)返回%模数而不是余数(取决于语言,负整数的mod操作可能会略有不同)
prev(index) = (index-1) % len(array)
%
mod
int m(int a,int b){ return (a % b + b) % b; }
所以你只需定义prev(n) = m(n-1,len(array))
prev(n) = m(n-1,len(array))