Explain, please, such cycles, anywhere did not meet it:
for (i = p;i != id[i];i = id[i]); for (j = q;j != id[j];j = id[j]);
This example is from Sagewick Robert-Algorithms in C ++. Fast connectivity solution.
I understand that your problem, at least in part, lies in misunderstanding the logic of the work of for
, so you should start with this.
According to msdn :
for (init-expression; cond-expression; loop-expression) statement;
init-expression
is executed only once before any other element of the for
operator, and then cond-expression
is passed control.cond-expression
is executed before each iteration of the statement
, including the first iteration. statement
is executed only if cond-expression
is true
(in fact, a value other than 0
)loop-expression
is executed at the end of each iteration of the statement
. After loop-expression
executed, the cond-expression
Thus, there are no severe restrictions on for elements that are not imposed (and it is worth noting that they may not exist at all, for example, an infinite loop: for (;true;)
or even so for (;;)
)
Regarding your example: for (i = p; i != id[i]; i = id[i]);
Starting with the index p
before entering the body of the for
( statement
) itself, there is a check for the fact that the index and the array element are unequal at this index ( i != id[i]
); Then the index is changed to an element of the array at this index ( i = id[i]
), and again i != id[i]
is checked, and so on.
As you are told in a comment, this is often used when several lists are put into one array. In this case, the element with the index i
array id
( id[i]
) stores the next / previous element for the list containing i
.
And, apparently, at the end of each such "list" stored in this array, there must be an element that duplicates the initial one, otherwise the condition for completing the cycle is unattainable and sooner or later the output will simply go beyond the array boundaries with nonstandard lists with overridden operator[]
behavior or something like that).
Source: https://ru.stackoverflow.com/questions/499806/
All Articles
for
, otherwise he would not ask such a question. - StateItPrimitive