mercredi 14 septembre 2016

From integer-indexed for loop enumeration to range-for

I have some code that enumerates some data, something like this:

int count;
InitDataEnumeration(/* some init params */, &count);

for (int i = 0; i < count; i++) 
{ 
    EnumGetData(i, &data);
    // process data ...
}

I'd like to convert this code in a form suitable to C++11's range-for.

I was thinking of defining a DataEnumerator wrapper class, whose constructor would call the above InitDataEnumeration() function.

The idea would be to use this wrapper class like this:

DataEnumerator enumerator{/* init params*/};

for (const auto& data : enumerator) 
{
    // process data ...
}

How could the former int-indexed for loop be refactored in the latter range-based form?

I was thinking of exposing begin() and end() methods from the enumerator wrapper class, but I don't know what kind of iterators they should return, and how to define such iterators.

Note that the iteration process is forward-only.

Aucun commentaire:

Enregistrer un commentaire