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.

  • What's the problem? Normal cycles ... Initializing a variable; loop continuation condition; operator for each iteration. - Vladimir Martyanov
  • 2
    I often saw this when several lists were put in one array. The id [i] field stores the next (and usually previous) item for the list containing i - pavel
  • It seems to me that the person is simply not clear about the sequence of actions to be taken (and which particular actions may be in it) and checks in for , otherwise he would not ask such a question. - StateItPrimitive
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

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; 
  1. init-expression is executed only once before any other element of the for operator, and then cond-expression is passed control.
  2. 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 )
  3. 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).