Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Behaviour with List in C++

I was writing a program for Euler circuit, but the program didn’t give the right output.

Adding a seemingly unrelated line of code got it to work. Can someone decode what just happened?

Snippet of the original program:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/* A is a vector of lists that, where A[i] is the list of edges from vertex i. */
/* perform checks for even degree, then find a non-isolated vertex to begin the tour */
int u;
for (u = 0; u < A.size() && A[u].empty(); u++)
while (!A[u].empty()) {
    cout << u << "->";
    int v = A[u].front();
    A[u].pop_front();
    u = v;
}
cout << u << endl;

The line that I added after the end of for loop:

cout << u << A[u].size() << endl;

>Solution :

Let me rewrite your snippet with more accurate indentation and some braces added for clarity:

int u;
for (u = 0; u < A.size() && A[u].empty(); u++)
{
    while (!A[u].empty()) {
        cout << u << "->";
        int v = A[u].front();
        A[u].pop_front();
        u = v;
    }
}
cout << u << endl;

Notice that the while loop is inside the for loop. But if we’re in the for loop, then A[u].empty() is true, so !A[u].empty() is false, so the while loop is never entered.

When you added a line "after" the for loop, you made that one line what the for loop executes:

int u;
for (u = 0; u < A.size() && A[u].empty(); u++)
{
    cout << u << A[u].size() << endl;
}
while (!A[u].empty()) {
    cout << u << "->";
    int v = A[u].front();
    A[u].pop_front();
    u = v;
}
cout << u << endl;

Now, you have the intended behavior: A for loop that increments u, followed by a separate while loop that acts on u.

To get the original behavior while still having the first for loop do nothing, actually give your for loop an empty body:

int u;
for (u = 0; u < A.size() && A[u].empty(); u++) { }
while (!A[u].empty()) {
    cout << u << "->";
    int v = A[u].front();
    A[u].pop_front();
    u = v;
}
cout << u << endl;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading