niksrb niksrb - 1 month ago 5
C++ Question

Parallell while loops without using threads

(C++)
Is there any possibility to run two parallel while loops without using threads? I have tried putting them one after another, both in one for loop, but it doesn't work for me because the variable that I'm using in while condition is getting changed through 1st loop and I need it to be the same for both loops.
Here's the code:

for (size_t j = 0; j < word.length(); j++)
{
while (word[j] != tmp->data)
{
counter1++;
tmp = tmp->next;
}
while (word[j] != tmp->data)
{
counter2++;
tmp = tmp->previous;
}
}

Answer

From the comment:

I'm getting the letter from a string and trying to find out which path is shorter to get to the same letter in alphabet, going forward or backwards. I am using cyclical doubly linked list.

Sounds like you just want one while loop with two tmp pointers:

for (size_t j = 0; j < word.length(); j++)
{       
    while (word[j] != tmp1->data && word[j] != tmp2->data)
    {
        counter++;
        tmp1 = tmp1->next;
        tmp2 = tmp2->previous;
    }       
}
Comments