Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to refactor this while loop to get rid of "continue"?
    primarykey
    data
    text
    <p>I have a <code>while (!Queue.empty())</code> loop that processes a queue of elements. There are a series of pattern matchers going from highest-priority to lowest-priority order. When a pattern is matched, the corresponding element is removed from the queue, and matching is restarted from the top (so that the highest-priority matchers get a chance to act first).</p> <p>So right now it looks something like this (a simplified version):</p> <pre><code>while (!Queue.empty()) { auto &amp; Element = *Queue.begin(); if (MatchesPatternA(Element)) { // Highest priority, since it's first // Act on it // Remove Element from queue continue; } if (MatchesPatternB(Element)) { // Act on it // Remove Element from queue continue; } if (MatchesPatternC(Element)) { // Lowest priority, since it's last // Act on it // Remove Element from queue continue; } // If we got this far, that means no pattern was matched, so // Remove Element from queue } </code></pre> <p>This works, but I want to refactor this loop in some way to remove the use of the keyword <code>continue</code>.</p> <p>Why? Because if I want to outsource a pattern matching to an external function, it obviously breaks. E.g.</p> <pre><code>void ExternalMatching(...) { if (MatchesPatternB(Element)) { // Act on it // Remove Element from queue continue; // This won't work here } } while (!Queue.empty()) { auto &amp; Element = *Queue.begin(); if (MatchesPatternA(Element)) { // Act on it // Remove Element from queue continue; } ExternalMatching(...); if (MatchesPatternC(Element)) { // Act on it // Remove Element from queue continue; } // If we got this far, that means no pattern was matched, so // Remove Element from queue } </code></pre> <p>I don't want to have to write repetitive if statements like <code>if (ExternalMatching(...)) { ... continue; }</code>, I'd rather find a cleaner way to express this logic.</p> <p>This simplified example might make it seem like a good idea to make pattern matching more general rather than having distinct <code>MatchesPatternA</code>, <code>MatchesPatternB</code>, <code>MatchesPatternC</code>, etc. functions. But in my situation the patterns are quite complicated, and I'm not quite ready to generalize them yet. So I want to keep that part as is, separate functions.</p> <p>Any elegant ideas? Thank you!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload