jeudi 21 décembre 2017

Clean for loop for matching elements

I find that a lot of code I write in general is following a pattern of "loop through this container and do X to elements that match some criteria".

which often looks like this:

std::vector<int> theList(10);
std::iota(theList.begin(), theList.end(), 0);

for (auto i : theList)
{
    if ((i % 2) == 0)
    {
        //Do something with i
    }
}

I don't like the if statements in these cases - they're ugly and detract from what is really happening in the logic of the loop.

What I'd like is a better way of doing this so the heart of the problem is expressed nicely.

My best attempt so far isn't all that nice:

std::vector<int> theList(10);
std::iota(theList.begin(), theList.end(), 0);

auto criteria = [](const int& i) -> bool { return (i % 2) == 0; };

for (auto it = std::find_if(theList.begin(), theList.end(), criteria);
     it != theList.end();
     it = std::find_if(++it, theList.end(), criteria)
     )
{
    std::cout << *it << ", ";
}

It feels like this pattern should make its way in to std::algorithm in a cleaner way.

Is there a better way of doing this?

Aucun commentaire:

Enregistrer un commentaire