Search code examples
c++foreachc++-clicontinue

How to go to next within for each loop


I recently needed to modify someone's code that used multiple continue cases in a for each. The addition was a new control loop inside the for each, which promptly broke the continue logic. Is there a good way to get the next list item in a such a loop without rewriting all of the continue cases?

// Additional control loops within the member function which cannot be 
// turned into functions due to native C++ data types.
{
    for each(KeyValuePair<String^,String^> kvp in ListOfItems) {
        do { // new condition testing code
           // a bunch of code that includes several chances to continue
        } while (!reachedCondition)
    }
}

Solution

  • continue and break go to the inner most control loop. I've used the iterator within a for loop. So depending upon what your ListOfItems is (i.e. SortedList or Dictionary ...) you might be able to iterate instead of continue.

    int i=0;
    Dictionary^ d = gcnew Dictionary<string, string>();
    
    for (IEnumerator<KeyValuePair<string, string>>^ e =  d->GetEnumerator();i< d->Count;i++) {
        // do stuff
        e->MoveNext();
    }