¿Expresión más concisa/eficiente para una lista cíclica?
Frecuentes
Visto 131 veces
1
What is the most concise/efficient function (in C++) to convert a "cyclic" index in a real index ?
My problem can be illustrated by the following image :
I have a real list (a C++ vector for instance) of size size
containing elements (here A, B, C, D, E
). In order to mimic a "cyclic" list I am searching for a function to convert an input index (from -inf
a +inf
) to the real index of the list. With this function and the image example the code :
for(i=-10; i < 10; ++i) std::cout<<list[myFunction(i, list.size())]<<" ";
will print 4 times the list as displayed in the image.
My current expression of myFunction
es:
inline int myFunction(const int i, const int size)
{
return (i >= 0) ? (i%size) : ((size-((-i)%size))%size);
}
Do you think that there is a more simple/concise/efficient way to write this ?
3 Respuestas
3
There are a couple of more concise ways of representing this. Both involve the fact that if i < 0
, (i % size) + size
is the number you are looking for. So, you can use
inline int myFunction(const int i, const int size)
{
int index = i % size;
return (index<0) ? (index+size) : index;
}
OR
inline int myFunction(const int i, const int size)
{
return (((i%size)+size)%size);
}
Respondido 25 ago 12, 22:08
1
size_t myFunction (const int i, const size_t size)
{
return (i - (i<1)) % size;
}
Concise, but not very clear since it exploits the bool/int conversions. I'd prefer an STL compliant circular buffer (like for example the boost implementation http://www.boost.org/doc/libs/1_50_0/libs/circular_buffer/doc/circular_buffer.html)
Respondido 25 ago 12, 22:08
Note that the sign of the result of the %
operator is implementation-defined if either operand is negative in the '98 standard. - aib
0
I would suggest overloading the [] operator
. As for the math, see @murgatroid99's answer.
Respondido 25 ago 12, 23:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c++ algorithm list modulo or haz tu propia pregunta.
Why are you checking if index < 0? size is going to be 5 in this case, and the array goes from 0 to 4. i % size will give you a number from 0 to size - 1. return i % size, is good enough. - JustinDanielson
Because taking the modulus of a negative number can return a negative number (so
-8%5
puede regresar-3
) - murgatroid99