C++ modulus operator circular array

C + +模运算符的圆形阵列

Tags: c++ modulus
标签: c++ modulus

问题 (Question)

I am trying to achieve a "wrap around" effect in a circular array. When I push an item to front, I want it to be stored in decreasing locations. When I push to front, I'm trying something like this:

items[front] = ch;
    front = (front - 1) % capacity; 

But this does not wrap around like I would expect. Front starts out at 0, and when the second line executes, front becomes -1. Shouldn't front become 6 after the second line executes? My data structures textbook seems to think so.

我试着去完成一个“缠绕”的影响,一个圆形阵列。当我把一个项目前,我想这是存储在降低的位置。当我推到前面,我想这样的事情:

items[front] = ch;
    front = (front - 1) % capacity; 

但这不环绕像我期望。前开始于0,和第二行执行时,面前变得- 1。不应该成为第二行执行前6后?我的数据结构教材似乎是这么认为的。

最佳答案 (Best Answer)

That is how % works in c++. To get the effect you want try this:

front = (front + capacity - 1) % capacity; 

那是怎样的%在C + +的作品。你想要试试看这个:

front = (front + capacity - 1) % capacity; 

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23451511